Cotton code
538 lines · 23.3 KB · SwiftRaw
// The call's media: Google's WebRTC (stasel's build, `Package.swift`).//// One peer connection per one-to-one call, unified plan, one bundle. The// microphone track always; the front camera's track on a video call. What the// peer makes here (the offer or the answer, each ICE candidate) goes back to// the core as `calls.signal { out }`, and the ICE connection's state as// `calls.media`; what the core hands (the remote description, a candidate, an// ICE restart) is applied here. DTLS-SRTP end to end; TURN relays only// encrypted packets.//// A group call (chat/CONTRACT.md "Group calls", "The media") has one// connection to the SFU instead: this phone's microphone (and camera) pushed// as send-only transceivers of their own, and each other person's tracks// pulled in the SFU's offers, kept as theirs by mid: their video to their// tile, their voice as its own track (for Take notes). SFU ops go one at a// time. DTLS-SRTP to the SFU, which could read it: "Protected in transit".#if os(iOS)import AVFoundationimport Foundationimport Observationimport WebRTC/// The tracks a call's screen draws: this phone's camera and the other side's video; on a group call each/// person's video by the room's member id, one tile each.@MainActor@Observablepublic final class CallVideo {    public fileprivate(set) var local: RTCVideoTrack?    public fileprivate(set) var remote: RTCVideoTrack?    public fileprivate(set) var remotes: [String: RTCVideoTrack] = [:]    public init() {}}@MainActorpublic final class WebRTCPeer: NSObject, CallPeerPort {    public let video = CallVideo()    private let factory: RTCPeerConnectionFactory    private var connection: RTCPeerConnection?    private var events: CallPeerEvents?    private var audioTrack: RTCAudioTrack?    private var videoTrack: RTCVideoTrack?    private var videoSource: RTCVideoSource?    private var capturer: RTCCameraVideoCapturer?    private var log: @Sendable (String) -> Void    // 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    /// Whether this call carries video (the camera is pushed as its own transceiver).    private var sfuVideo = false    /// Whose each pulled transceiver is, by mid (the room says it with each offer).    private var owners: [String: String] = [:]    /// Each person's own audio track, by member: one stream per person, as Take notes needs.    public private(set) var voices: [String: RTCAudioTrack] = [:]    /// SFU ops wait their turn: a description is set only once the one before it is.    private var queue: [(@escaping @MainActor () -> Void) -> Void] = []    private var running = false    private var speakingNow = false    private var loud = 0    private var quiet = 0    /// The microphone's audio level (0…1) above which this phone is talking (as Android).    static let speakingLevel = 0.03    public init(log: @escaping @Sendable (String) -> Void = { _ in }) {        RTCInitializeSSL()        factory = RTCPeerConnectionFactory(            encoderFactory: RTCDefaultVideoEncoderFactory(),            decoderFactory: RTCDefaultVideoDecoderFactory()        )        self.log = log        super.init()    }    public func create(offerer: Bool, iceServers: [CallIceServer], video: Bool, events: CallPeerEvents) {        close()        self.events = events        guard let connection = open(iceServers) else { return }        let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)        let audio = factory.audioTrack(with: factory.audioSource(with: constraints), trackId: "audio")        connection.add(audio, streamIds: ["cotton"])        audioTrack = audio        if video {            let source = factory.videoSource()            let track = factory.videoTrack(with: source, trackId: "video")            connection.add(track, streamIds: ["cotton"])            videoSource = source            videoTrack = track            self.video.local = track        }        if offerer { offer(restart: false) }    }    /// The peer connection itself over these servers (unified plan, one bundle); nil, and the media failed, when    /// WebRTC makes none.    private func open(_ iceServers: [CallIceServer]) -> RTCPeerConnection? {        let configuration = RTCConfiguration()        configuration.iceServers = iceServers.map { RTCIceServer(urlStrings: $0.urls, username: $0.username, credential: $0.credential) }        configuration.sdpSemantics = .unifiedPlan        configuration.bundlePolicy = .maxBundle        configuration.rtcpMuxPolicy = .require        configuration.continualGatheringPolicy = .gatherContinually        let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)        guard let connection = factory.peerConnection(with: configuration, constraints: constraints, delegate: self) else {            log("calls peer: WebRTC made no peer connection")            events?.media(.failed)            return nil        }        self.connection = connection        return connection    }    // MARK: A group call through the SFU    public func switchToSfu(iceServers: [CallIceServer], video: Bool, events: CallPeerEvents) {        close()        self.events = events        sfu = true        sfuVideo = video        guard open(iceServers) != nil else { return }        listen()    }    public func pushTracks(audio: Bool, video sending: Bool) {        turn { [weak self] done in            guard let self, let open = self.connection else { return done() }            // WebRTC calls back on its own thread; the connection is only touched again on the main actor.            nonisolated(unsafe) let made = open            let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)            let send = RTCRtpTransceiverInit()            send.direction = .sendOnly            send.streamIds = ["cotton"]            var pushed: [(RTCRtpTransceiver, String)] = []            let mic = self.factory.audioTrack(with: self.factory.audioSource(with: constraints), trackId: "audio")            mic.isEnabled = audio            self.audioTrack = mic            if let t = made.addTransceiver(with: mic, init: send) { pushed.append((t, "audio")) }            if self.sfuVideo {                let source = self.factory.videoSource()                let track = self.factory.videoTrack(with: source, trackId: "video")                track.isEnabled = sending                self.videoSource = source                self.videoTrack = track                self.video.local = track                if let t = made.addTransceiver(with: track, init: send) { pushed.append((t, "video")) }                if sending { self.startCamera() }            }            nonisolated(unsafe) let sent = pushed            made.offer(for: constraints) { description, error in                let sdp = description?.sdp                let failed = error.map { "\($0)" }                Task { @MainActor in                    guard let sdp else {                        self.log("calls sfu: no offer: \(failed ?? "")")                        return done()                    }                    made.setLocalDescription(RTCSessionDescription(type: .offer, sdp: sdp)) { error in                        let refused = error.map { "\($0)" }                        Task { @MainActor in                            if let refused {                                self.log("calls sfu: own offer refused: \(refused)")                            } else if self.connection === made {                                let tracks = sent.map { t, kind in CallSfuTrack(mid: t.mid, member: nil, name: "\(kind)-\(t.mid)", kind: kind) }                                self.events?.sfu("push", sdp, tracks, nil)                            }                            done()                        }                    }                }            }        }    }    public func applySfu(op: String, sdp: String, tracks: [CallSfuTrack]) {        turn { [weak self] done in            guard let self, let open = self.connection else { return done() }            // WebRTC calls back on its own thread; the connection is only touched again on the main actor.            nonisolated(unsafe) let made = open            let offer = op == "offer"            // The SFU's offer of others' tracks can come before its answer to this phone's own push: it waits.            if offer, made.signalingState == .haveLocalOffer {                DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(150)) { [weak self] in                    self?.applySfu(op: op, sdp: sdp, tracks: tracks)                }                return done()            }            for t in tracks { if let mid = t.mid, let member = t.member { self.owners[mid] = member } }            made.setRemoteDescription(RTCSessionDescription(type: offer ? .offer : .answer, sdp: sdp)) { error in                let refused = error.map { "\($0)" }                Task { @MainActor in                    if let refused {                        self.log("calls sfu: the SFU's \(op) was refused: \(refused)")                        return done()                    }                    guard offer, self.connection === made else {                        self.claim(made)                        return done()                    }                    made.answer(for: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)) { description, error in                        let answer = description?.sdp                        let failed = error.map { "\($0)" }                        Task { @MainActor in                            guard let answer else {                                self.log("calls sfu: no answer: \(failed ?? "")")                                return done()                            }                            made.setLocalDescription(RTCSessionDescription(type: .answer, sdp: answer)) { error in                                let refused = error.map { "\($0)" }                                Task { @MainActor in                                    if let refused {                                        self.log("calls sfu: own answer refused: \(refused)")                                    } else if self.connection === made {                                        self.events?.sfu("renegotiate", answer, nil, nil)                                        self.claim(made)                                    }                                    done()                                }                            }                        }                    }                }            }        }    }    /// Every pulled transceiver's track, kept as its person's: their video for the tile, their voice apart.    private func claim(_ made: RTCPeerConnection) {        for t in made.transceivers {            guard let member = owners[t.mid] else { continue }            if let track = t.receiver.track as? RTCVideoTrack {                if video.remotes[member] !== track { video.remotes[member] = track }            } else if let track = t.receiver.track as? RTCAudioTrack {                voices[member] = track            }        }    }    public func closeTracks(member: String) {        video.remotes[member] = nil        voices[member] = nil        let mids = owners.filter { $0.value == member }.map(\.key).sorted()        mids.forEach { owners[$0] = nil }        if !mids.isEmpty { events?.sfu("close", nil, nil, mids) }    }    /// One SFU op at a time: `work` calls its `done` once its descriptions are set.    private func turn(_ work: @escaping (@escaping @MainActor () -> Void) -> Void) {        queue.append(work)        if !running { next() }    }    private func next() {        guard !queue.isEmpty else {            running = false            return        }        running = true        let work = queue.removeFirst()        work { [weak self] in self?.next() }    }    /// This phone's own voice from the microphone's level (`media-source` stats), said on a change: on after two    /// loud looks, off after five quiet ones, looks 200 ms apart (as Android).    private func listen() {        guard let open = connection else { return }        nonisolated(unsafe) let made = open        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) { [weak self] in            guard let self, self.connection === made, self.sfu else { return }            made.statistics { report in                let level = report.statistics.values.first { $0.type == "media-source" && ($0.values["kind"] as? String) == "audio" }?                    .values["audioLevel"] as? NSNumber                let heard = level?.doubleValue ?? 0                Task { @MainActor in                    guard self.connection === made else { return }                    self.hear(heard)                    self.listen()                }            }        }    }    /// One look at the microphone's level.    func hear(_ level: Double) {        let on = audioTrack?.isEnabled == true && level > Self.speakingLevel        if on { loud += 1; quiet = 0 } else { quiet += 1; loud = 0 }        if !speakingNow, loud >= 2 { speakingNow = true; events?.speaking(true) }        if speakingNow, quiet >= 5 { speakingNow = false; events?.speaking(false) }    }    public func applyRemote(kind: CallSignalKind, sdp: String) {        guard let connection else { return }        let type: RTCSdpType = kind == .answer ? .answer : .offer        connection.setRemoteDescription(RTCSessionDescription(type: type, sdp: sdp)) { [weak self] error in            let failed = error.map { "\($0)" }            Task { @MainActor in                guard let self else { return }                if let failed {                    self.log("calls peer: the remote description was refused: \(failed)")                    return                }                if kind != .answer { self.answer() }            }        }    }    public func addCandidate(_ candidate: String, mid: String?, mline: Int?) {        let ice = RTCIceCandidate(sdp: candidate, sdpMLineIndex: Int32(mline ?? 0), sdpMid: mid)        connection?.add(ice) { [log] error in            if let error { log("calls peer: a candidate was refused: \(error)") }        }    }    public func restartIce() {        // The SFU keeps its side of the connection; this phone's ICE gathers again by itself (continual gathering).        if sfu {            log("calls sfu: the connection dropped; ICE gathers again by itself")            return        }        offer(restart: true)    }    public func close() {        capturer?.stopCapture()        capturer = nil        connection?.close()        connection = nil        audioTrack = nil        videoTrack = nil        videoSource = nil        video.local = nil        video.remote = nil        video.remotes = [:]        voices = [:]        owners = [:]        queue = []        running = false        sfu = false        sfuVideo = false        speakingNow = false        loud = 0        quiet = 0        events = nil    }    public func setSending(audio: Bool, video sending: Bool) {        audioTrack?.isEnabled = audio        videoTrack?.isEnabled = sending        if sending, capturer == nil, videoTrack != nil { startCamera() }        if !sending { stopCamera() }    }    /// Which camera a call's picture comes from: the front one first.    private var facing: AVCaptureDevice.Position = .front    /// The other camera, at once if it is on.    public func flipCamera() {        facing = facing == .front ? .back : .front        guard capturer != nil else { return }        stopCamera()        startCamera()    }    /// The facing camera at 720p and 30 fps (a one-to-one call).    public func startCamera() {        guard let videoSource, capturer == nil,              let device = RTCCameraVideoCapturer.captureDevices().first(where: { $0.position == facing })                ?? RTCCameraVideoCapturer.captureDevices().first        else { return }        let formats = RTCCameraVideoCapturer.supportedFormats(for: device)        let wanted: Int32 = 1280 * 720        let format = formats.min { a, b in            let da = CMVideoFormatDescriptionGetDimensions(a.formatDescription)            let db = CMVideoFormatDescriptionGetDimensions(b.formatDescription)            return abs(da.width * da.height - wanted) < abs(db.width * db.height - wanted)        }        guard let format else { return }        let fps = min(30, Int(format.videoSupportedFrameRateRanges.map(\.maxFrameRate).max() ?? 30))        let capturer = RTCCameraVideoCapturer(delegate: videoSource)        // The camera goes on while the call is in picture in picture.        if capturer.captureSession.isMultitaskingCameraAccessSupported {            capturer.captureSession.isMultitaskingCameraAccessEnabled = true        }        capturer.startCapture(with: device, format: format, fps: fps)        self.capturer = capturer    }    public func stopCamera() {        capturer?.stopCapture()        capturer = nil    }    // MARK: Descriptions made here    private func offer(restart: Bool) {        guard let connection else { return }        let mandatory = restart ? [kRTCMediaConstraintsIceRestart: kRTCMediaConstraintsValueTrue] : nil        connection.offer(for: RTCMediaConstraints(mandatoryConstraints: mandatory, optionalConstraints: nil)) { [weak self] description, error in            let sdp = description?.sdp            let failed = error.map { "\($0)" }            Task { @MainActor in                guard let self else { return }                guard let sdp else {                    self.log("calls peer: no offer: \(failed ?? "")")                    return                }                self.setLocal(type: .offer, sdp: sdp, kind: restart ? .restart : .offer)            }        }    }    private func answer() {        guard let connection else { return }        connection.answer(for: RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)) { [weak self] description, error in            let sdp = description?.sdp            let failed = error.map { "\($0)" }            Task { @MainActor in                guard let self else { return }                guard let sdp else {                    self.log("calls peer: no answer: \(failed ?? "")")                    return                }                self.setLocal(type: .answer, sdp: sdp, kind: .answer)            }        }    }    private func setLocal(type: RTCSdpType, sdp: String, kind: CallSignalKind) {        guard let connection else { return }        connection.setLocalDescription(RTCSessionDescription(type: type, sdp: sdp)) { [weak self] error in            let failed = error.map { "\($0)" }            Task { @MainActor in                guard let self else { return }                if let failed {                    self.log("calls peer: the local description was refused: \(failed)")                    return                }                self.events?.signal(kind, sdp, nil, nil, nil)            }        }    }}extension WebRTCPeer: RTCPeerConnectionDelegate {    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {}    nonisolated public func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {}    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCPeerConnectionState) {        let raw = newState.rawValue        Task { @MainActor in self.log("calls peer: connection \(raw) (0 new, 1 connecting, 2 connected, 3 disconnected, 4 failed, 5 closed)") }    }    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {        let raw = newState.rawValue        Task { @MainActor in self.log("calls peer: ice \(raw) (0 new, 1 checking, 2 connected, 3 completed, 4 failed, 5 disconnected, 6 closed)") }        let state: CallMediaState? = switch newState {        case .connected, .completed: .connected        case .disconnected: .disconnected        case .failed: .failed        default: nil        }        guard let state else { return }        Task { @MainActor in self.events?.media(state) }    }    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {        let sdp = candidate.sdp        let mid = candidate.sdpMid        let mline = Int(candidate.sdpMLineIndex)        Task { @MainActor in self.events?.signal(.ice, nil, sdp, mid, mline) }    }    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didAdd rtpReceiver: RTCRtpReceiver, streams mediaStreams: [RTCMediaStream]) {        guard let track = rtpReceiver.track as? RTCVideoTrack else { return }        nonisolated(unsafe) let remote = track        Task { @MainActor in            // A group call's tracks are each person's, claimed by mid once the answer is set.            guard !self.sfu else { return }            self.video.remote = remote        }    }    nonisolated public func peerConnection(_ peerConnection: RTCPeerConnection, didStartReceivingOn transceiver: RTCRtpTransceiver) {        nonisolated(unsafe) let made = peerConnection        Task { @MainActor in            guard self.sfu, self.connection === made else { return }            self.claim(made)        }    }}/// The audio session for a call, as WebRTC takes it under CallKit: manual/// audio, so WebRTC's audio unit starts only when CallKit has activated the/// session (`activated`), never when the app would.@MainActorpublic final class CallAudioSession: CallAudioPort {    private let session = RTCAudioSession.sharedInstance()    public init() {        session.useManualAudio = true        session.isAudioEnabled = false    }    public func configure(video: Bool) {        session.lockForConfiguration()        defer { session.unlockForConfiguration() }        do {            try session.setCategory(.playAndRecord, mode: video ? .videoChat : .voiceChat, options: [.allowBluetoothHFP, .allowBluetoothA2DP])        } catch {            // Said on the screen by the call's silence; nothing else can be done here.        }    }    public func stop() {        session.isAudioEnabled = false    }    public func activated() {        session.audioSessionDidActivate(AVAudioSession.sharedInstance())        session.isAudioEnabled = true    }    public func deactivated() {        session.audioSessionDidDeactivate(AVAudioSession.sharedInstance())        session.isAudioEnabled = false    }    public func setSpeaker(_ on: Bool) {        session.lockForConfiguration()        defer { session.unlockForConfiguration() }        try? session.overrideOutputAudioPort(on ? .speaker : .none)    }}#endif