// What the call engine performs its effects ON: one port per system.//// The live ports are CallKit (`CallKitSystem`), URLSession's socket// (`WebSocketCallSocket`), WebRTC's peer and camera (`WebRTCPeer`), the audio// session (`CallAudioSession`), the ringback (`RingbackTone`) and a clock. The// tests hand fakes of every one (`Tests/CottonCallsTests`), so each effect is// checked to reach its port without a phone, a network or a camera.importCottonKitimportFoundation/// The system's call UI: CallKit on an iPhone.@MainActorpublicprotocolSystemCallPort: AnyObject {/// An outgoing call starts (`CXStartCallAction`).func startOutgoing(uuid: UUID, handle: String, name: String?, video: Bool)func outgoingConnecting(uuid: UUID)func outgoingConnected(uuid: UUID)/// A ring here (`reportNewIncomingCall`). A call the push already reported/// is updated instead: iOS takes one report per call. `handle` is the/// caller's number when the ring's box named them.func reportIncoming(uuid: UUID, title: String, handle: String?, video: Bool)func update(uuid: UUID, handle: String, name: String?, video: Bool)/// The call is over: `reason` is `CXCallEndedReason`'s raw value, or none/// to ask a `CXEndCallAction` (this person ended it).func ended(uuid: UUID, reason: Int?)}/// The room's socket.@MainActorpublicprotocolCallSocketPort: AnyObject {/// Open `url` with `Authorization: Bearer <credential>`. Each text frame/// arrives at `received`; a close nobody asked for at `closed`.funcopen(url: URL, credential: String, received: @escaping @MainActor (JSONValue) -> Void, closed: @escaping @MainActor () -> Void)/// Send one frame; frames handed before the socket opens go once it does.func send(_ frame: JSONValue)func close()}/// What the peer hands back to the core.publicstructCallPeerEvents: Sendable {/// A description or candidate made here: `calls.signal { out }`.publicvar signal: @MainActor @Sendable (_ kind: CallSignalKind, _ sdp: String?, _ candidate: String?, _ mid: String?, _ mline: Int?) -> Void/// The ICE connection's state: `calls.media`.publicvar media: @MainActor @Sendable (CallMediaState) -> Void/// A group call's SFU op made here (`push` with its tracks, `renegotiate`, `close` with mids):/// `calls.signal { out: { sfu } }`.publicvar sfu: @MainActor @Sendable (_ op: String, _ sdp: String?, _ tracks: [CallSfuTrack]?, _ mids: [String]?) -> Void/// This phone's own voice started or stopped (a group call): `calls.speaking`.publicvar speaking: @MainActor @Sendable (Bool) -> Voidpublicinit( signal: @escaping @MainActor @Sendable (CallSignalKind, String?, String?, String?, Int?) -> Void, media: @escaping @MainActor @Sendable (CallMediaState) -> Void, sfu: @escaping @MainActor @Sendable (String, String?, [CallSfuTrack]?, [String]?) -> Void = { _, _, _, _ in }, speaking: @escaping @MainActor @Sendable (Bool) -> Void = { _ in } ) {self.signal = signalself.media = mediaself.sfu = sfuself.speaking = speaking }}/// The peer connection, its tracks and the camera: WebRTC.@MainActorpublicprotocolCallPeerPort: AnyObject {/// Make the peer over these servers, its microphone track (and camera/// track for a video call) added. The offerer makes its offer at once.func create(offerer: Bool, iceServers: [CallIceServer], video: Bool, events: CallPeerEvents)/// Set the remote description; an offer or a restart is answered.func applyRemote(kind: CallSignalKind, sdp: String)func addCandidate(_ candidate: String, mid: String?, mline: Int?)/// A restart offer, handed back as `restart`.func restartIce()func close()func setSending(audio: Bool, video: Bool)/// The front camera: 720p at 30 fps for a one-to-one call.func startCamera()func stopCamera()// A group call (chat/CONTRACT.md "Group calls"): one connection to the SFU, this phone's tracks pushed, each// person's pulled and kept as theirs. SFU ops go one at a time./// Make the one connection to the SFU (any peer-to-peer one closed first).func switchToSfu(iceServers: [CallIceServer], video: Bool, events: CallPeerEvents)/// Add the microphone (and camera) as send-only transceivers, offer them, hand back `push` with each mid.func pushTracks(audio: Bool, video: Bool)/// The SFU's answer to a push, or its offer of others' tracks (`tracks` say whose each mid is), answered/// with `renegotiate`.func applySfu(op: String, sdp: String, tracks: [CallSfuTrack])/// `member` left: their tracks go, and `close` is handed back for their mids.func closeTracks(member: String)}/// The audio session, held for a call.@MainActorpublicprotocolCallAudioPort: AnyObject {/// Configure for a call (voice or video chat). Not activated: CallKit/// activates it (`activated`).func configure(video: Bool)func stop()/// CallKit activated the session (`provider(_:didActivate:)`).func activated()func deactivated()/// The loudspeaker, a route of this phone's alone.func setSpeaker(_ on: Bool)}/// The ringback heard while the other phone rings.@MainActorpublicprotocolCallTonePort: AnyObject {func play(_ tone: String)func stop()}/// When to hand `calls.tick` back.@MainActorpublicprotocolCallClockPort: AnyObject {func after(milliseconds: Int, _ fire: @escaping @MainActor () -> Void)func cancelAll()}/// The core's `calls.*` methods, as the engine asks them.publicprotocolCallsCore: Sendable {func ask(_ method: String, _ request: JSONValue) asyncthrows -> JSONValue}/// The live core.publicstructCoreCalls: CallsCore {privatelet core: any CottonCallingpublicinit(core: any CottonCalling) {self.core = core }publicfunc ask(_ method: String, _ request: JSONValue) asyncthrows -> JSONValue {tryawait core.call(method, request, as: JSONValue.self) }}/// A `DispatchQueue.main` clock.@MainActorpublicfinalclassMainClock: CallClockPort {privatevar pending: [DispatchWorkItem] = []publicinit() {}publicfunc after(milliseconds: Int, _ fire: @escaping @MainActor () -> Void) {let item = DispatchWorkItem { MainActor.assumeIsolated { fire() } } pending.append(item)DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(max(0, milliseconds)), execute: item) }publicfunc cancelAll() { pending.forEach { $0.cancel() } pending.removeAll() }}