WebRTC Swift 2020

WebRTC

1 两个设备使用关于STUN服务器,TURN服务器,输入源(例如输入音频,输入视频)的配置来创建对等连接。
2 设备A和设备B向STUN服务器发送请求以获取其公共IP地址。
3 设备A通过信令服务器向设备B发送要约SDP和ICE候选者。
4 设备B还通过信令服务器将答案SDP和ICE候选发送到设备A。此时,两个设备可以通过对等连接一起交谈。

创建和配置对等连接

创建对等连接,您需要传递一个包含STUN和TURN服务器以及一些其他信息的配置。

func createPeerConnection() {
    let config = RTCConfiguration()
    config.iceServers = [RTCIceServer(urlStrings: iceServers)]
    
    // Unified plan is more superior than planB
    config.sdpSemantics = .unifiedPlan
    
    // gatherContinually will let WebRTC to listen to any network changes and send any new candidates to the other client
    config.continualGatheringPolicy = .gatherContinually
    
    let constraints = RTCMediaConstraints(
      mandatoryConstraints: nil,
      optionalConstraints: ["DtlsSrtpKeyAgreement": kRTCMediaConstraintsValueTrue])
    self.peerConnection = WebRTCClient.factory.peerConnection(with: config, constraints: constraints, delegate: self)
    
    self.createMediaSenders()
    self.configureAudioSession()
  }

创建音频轨道,视频轨道,并将它们添加到对等连接中,如下所示:

private func createMediaSenders() {
    let streamId = "stream"
    
    // Audio
    let audioTrack = self.createAudioTrack()
    self.peerConnection!.add(audioTrack, streamIds: [streamId])
    
    // Video
    let videoTrack = self.createVideoTrack()
    self.localVideoTrack = videoTrack
    self.peerConnection!.add(videoTrack, streamIds: [streamId])
    self.remoteVideoTrack = self.peerConnection!.transceivers.first { $0.mediaType == .video }?.receiver.track as? RTCVideoTrack
    
    // Data
    if let dataChannel = createDataChannel() {
      dataChannel.delegate = self
      self.localDataChannel = dataChannel
    }
  }
  
  private func createAudioTrack() -> RTCAudioTrack {
    let audioConstrains = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)
    let audioSource = WebRTCClient.factory.audioSource(with: audioConstrains)
    let audioTrack = WebRTCClient.factory.audioTrack(with: audioSource, trackId: "audio0")
    return audioTrack
  }
  
  private func createVideoTrack() -> RTCVideoTrack {
    let videoSource = WebRTCClient.factory.videoSource()
    
    #if TARGET_OS_SIMULATOR
    self.videoCapturer = RTCFileVideoCapturer(delegate: videoSource)
    #else
    self.videoCapturer = RTCCameraVideoCapturer(delegate: videoSource)
    #endif
    
    let videoTrack = WebRTCClient.factory.videoTrack(with: videoSource, trackId: "video0")
    return videoTrack
  }
  
  // MARK: Data Channels
  private func createDataChannel() -> RTCDataChannel? {
    let config = RTCDataChannelConfiguration()
    guard let dataChannel = self.peerConnection!.dataChannel(forLabel: "WebRTCData", configuration: config) else {
      debugPrint("Warning: Couldn't create data channel.")
      return nil
    }
    return dataChannel
  }

创建本地的SDP并将发送给其他人

func offer(completion: @escaping (_ sdp: RTCSessionDescription) -> Void) {
    let constrains = RTCMediaConstraints(
      mandatoryConstraints: self.mediaConstrains,
      optionalConstraints: nil)
    self.peerConnection!.offer(for: constrains) { (sdp, error) in
      guard let sdp = sdp else {
        return
      }
      
      self.peerConnection!.setLocalDescription(sdp, completionHandler: { (error) in
        completion(sdp)
      })
    }
  }
  
  func send(sdp rtcSdp: RTCSessionDescription, to person: String) {
    do {
      let dataMessage = try self.encoder.encode(SessionDescription(from: rtcSdp))
      let dict = try JSONSerialization.jsonObject(with: dataMessage, options: .allowFragments) as! [String: Any]
      Firestore.firestore().collection(person).document("sdp").setData(dict) { (err) in
        if let err = err {
          print("Error send sdp: \(err)")
        } else {
          print("Sdp sent!")
        }
      }
    }
    catch {
      debugPrint("Warning: Could not encode sdp: \(error)")
    }
  }

将本地候选人发送给其他人

func send(candidate rtcIceCandidate: RTCIceCandidate, to person: String) {
    do {
      let dataMessage = try self.encoder.encode(IceCandidate(from: rtcIceCandidate))
      let dict = try JSONSerialization.jsonObject(with: dataMessage, options: .allowFragments) as! [String: Any]
      Firestore.firestore()
        .collection(person)
        .document("candidate")
        .collection("candidates")
        .addDocument(data: dict) { (err) in
          if let err = err {
            print("Error send candidate: \(err)")
          } else {
            print("Candidate sent!")
          }
      }
    }
    catch {
      debugPrint("Warning: Could not encode candidate: \(error)")
    }
  }

收听远程SDP和候选人

func listenSdp(from person: String) {
    Firestore.firestore().collection(person).document("sdp")
      .addSnapshotListener { documentSnapshot, error in
        guard let document = documentSnapshot else {
          print("Error fetching sdp: \(error!)")
          return
        }
        guard let data = document.data() else {
          print("Firestore sdp data was empty.")
          return
        }
        print("Firestore sdp data: \(data)")
        do {
          let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
          let sessionDescription = try self.decoder.decode(SessionDescription.self, from: jsonData)
          self.delegate?.signalClient(self, didReceiveRemoteSdp: sessionDescription.rtcSessionDescription)
        }
        catch {
          debugPrint("Warning: Could not decode sdp data: \(error)")
          return
        }
    }
  }
  
  func listenCandidate(from person: String) {
    Firestore.firestore()
      .collection(person)
      .document("candidate")
      .collection("candidates")
      .addSnapshotListener { (querySnapshot, err) in
        guard let documents = querySnapshot?.documents else {
          print("Error fetching documents: \(err!)")
          return
        }

        querySnapshot!.documentChanges.forEach { diff in
          if (diff.type == .added) {
            do {
              let jsonData = try JSONSerialization.data(withJSONObject: documents.first!.data(), options: .prettyPrinted)
              let iceCandidate = try self.decoder.decode(IceCandidate.self, from: jsonData)
              self.delegate?.signalClient(self, didReceiveCandidate: iceCandidate.rtcIceCandidate)
            }
            catch {
              debugPrint("Warning: Could not decode candidate data: \(error)")
              return
            }
          }
        }
    }
  }

将 ans SDP发送到设备A

func answer(completion: @escaping (_ sdp: RTCSessionDescription) -> Void)  {
    let constrains = RTCMediaConstraints(mandatoryConstraints: self.mediaConstrains,
                                         optionalConstraints: nil)
    self.peerConnection!.answer(for: constrains) { (sdp, error) in
      guard let sdp = sdp else {
        return
      }
      
      self.peerConnection!.setLocalDescription(sdp, completionHandler: { (error) in
        completion(sdp)
      })
    }
  }

关闭对等连接

关闭对等连接,清除Firestore,重置变量并重新创建新的对等连接,以便为新会话做好准备

@IBAction func endCall(_ sender: Any) {
    self.signalClient.deleteSdpAndCandidate(for: self.currentPerson)
    self.webRTCClient.closePeerConnection()
    
    self.webRTCClient.createPeerConnection()
    self.hasLocalSdp = false
    self.localCandidateCount = 0
    self.hasRemoteSdp = false
    self.remoteCandidateCount = 0
  }
  
  func deleteSdpAndCandidate(for person: String) {
    Firestore.firestore().collection(person).document("sdp").delete() { err in
      if let err = err {
        print("Error removing firestore sdp: \(err)")
      } else {
        print("Firestore sdp successfully removed!")
      }
    }
    
    Firestore.firestore().collection(person).document("candidate").delete() { err in
      if let err = err {
        print("Error removing firestore candidate: \(err)")
      } else {
        print("Firestore candidate successfully removed!")
      }
    }
  }

func closePeerConnection() {
    self.peerConnection!.close()
    self.peerConnection = nil
  }

你可能感兴趣的:(WebRTC Swift 2020)