iOS开发iOS技术专题音视频知识库

iOS WebRTC的使用

2019-06-05  本文已影响126人  yitez

WebRTC是Google公司的一款跨平台的音视频通话技术,它为我们提供了音视频通信的核心技术,包括音视频的采集、编解码、网络传输、视频显示等功能。
借助这款API,我们可以更容易地实现音视频聊天功能。

准备工作:
1、两个客户端。
2、一台socket长连接服务器,用于交换客户端两端的通信信息(ip地址,端口等),以及管理通信状态等。
3、一台STUN/TURN/ICE Server,用于获取公网IP。

通信步骤:
1、客户端告知WebRTC获取公网地址的服务器的IP,整个过程中WebRTC会不断去获取公网地址,获取公网地址后,通过socket服务器发送给对方。
2、客户端拿到对方发送的公网地址,保存起来,WebRTC会在通信的时候选择最优的公网地址。
3、呼叫方生成一个类型为offer的会话描述,并设置为本地回话描述,然后通过socket服务器发送给接听方。
4、接听方收到offer的会话描述后,把offer设置为了远程回话描述。并生成一个类型为answer的回话描述,发送给呼叫方。
5、呼叫方收到接收方的answer,把answer设置为了远程回话描述。
6、至此,双方P2P连接建立,开始音视频通信。

具体实现:

@property(nonatomic, strong) RTCPeerConnection* peerConnection; 
@property(nonatomic, strong) RTCPeerConnectionFactory* peerConnectionFactory;   
@property(nonatomic, strong) RTCSessionDescription* localSdp;
@property(nonatomic, strong) RTCSessionDescription* remoteSdp;
@property(nonatomic, strong) RTCMediaConstraints* sdpMediaConstraints;
@property(nonatomic, strong) RTCAudioTrack* audioTrack;
@property(nonatomic, strong) RTCMediaStream* localMediaStream;
@property(nonatomic, strong) NSObject* candidateMutex;
@property(nonatomic, strong) NSMutableArray* queuedRemoteCandidates;
@property(nonatomic, strong) NSObject* sdpMutex;
@property(nonatomic, strong) NSMutableArray* queuedRemoteSdp;
@property(nonatomic, strong) RTCConfiguration *rtcConfig;
// video
@property(nonatomic, strong) RTCEAGLVideoView* localVideoView;
@property(nonatomic, strong) RTCEAGLVideoView* remoteVideoView;
@property(nonatomic, strong) RTCVideoTrack* localVideoTrack;
@property(nonatomic, strong) RTCVideoTrack* remoteVideoTrack;

接下来进行整体的初始化:
创建ConnectionFactory;

    #如果想要更加安全就开启SSL。
    [RTCPeerConnectionFactory initializeSSL];
    self.peerConnectionFactory = [[RTCPeerConnectionFactory alloc] init];

创建媒体流,并且添加音频轨道和视频轨道

    if (self.peerConnectionFactory) {
       # 初始化媒体流,ARDAMSa0和ARDAMS为专业标识符。
        self.localMediaStream = [self.peerConnectionFactory mediaStreamWithLabel:@"ARDAMS"];
        #添加音频轨道
        self.audioTrack = [self.peerConnectionFactory audioTrackWithID:@"ARDAMSa0"];
        [self.localMediaStream addAudioTrack:self.audioTrack];
        
        if (self.supportVideo) {
          #添加视频轨道
            self.localVideoTrack = [self createVideoTrack:self.useFrontFacingCamera];
            [self.localMediaStream addVideoTrack:self.localVideoTrack];
           #把本地视频轨道渲染到localVideoView
         [self.localVideoTrack  addRenderer:self.localVideoView];
        }
    }

创建媒体会话描述SDP:

   #配置信息的基础单元,以键值对的方式
   RTCPair* audio = [[RTCPair alloc] initWithKey:@"OfferToReceiveAudio" value:@"true"];
    NSArray* mandatory;
    if (self.supportVideo) {
        RTCPair* video = [[RTCPair alloc] initWithKey:@"OfferToReceiveVideo" value:@"true"];
        mandatory = @[ audio, video ];
    } else {
        mandatory = @[ audio ];
    }
    self.sdpMediaConstraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatory
                                                                     optionalConstraints:nil];
     #此处将ICEServers的ip地址和登录信息传递给RTC
    NSMutableArray *iceServers = [[NSMutableArray alloc] init];
        for(NSDictionary * dic in list)
        {
            NSString *strUsername = [dic objectForKey:@"userName"];
            NSString *strPassword = [dic objectForKey:@"password"];
            NSURL * strUri= [NSURL URLWithString:[dic objectForKey:@"uri"]];
            
            RTCICEServer * iceServer = [[RTCICEServer alloc] initWithURI:strUri username:strUsername password:strPassword];
            [iceServers addObject:iceServer];//jay for test
        }
      #config设置
    self.rtcConfig = [[RTCConfiguration alloc] init];
    self.rtcConfig.iceServers = iceServers;
    self.rtcConfig.iceConnectionReceivingTimeout = 90000; // 90s
    
    #没有使用DtlsSrtp加密。
    RTCPair *dtlssrtp = [[RTCPair alloc] initWithKey:@"DtlsSrtpKeyAgreement" value:@"false"];   //lianwei add for test
    RTCMediaConstraints *constraints = [[RTCMediaConstraints alloc] initWithMandatoryConstraints:mandatory optionalConstraints:@[dtlssrtp]];
     #创建peerConnection
    if (self.peerConnectionFactory) {
        self.peerConnection = [self.peerConnectionFactory peerConnectionWithConfiguration:self.rtcConfig
                                                                              constraints:constraints
                                                                                 delegate:self];
    }
      #把媒体流添加进peerConnection
    if (self.peerConnection) {
        [self.peerConnection addStream:self.localMediaStream];
    }

当我们将ICEServers告知RTC,且设置好peerConnection的delegate之后,如果获取到公网地址信息(ICECandidate),则会触发- (void)peerConnection:(RTCPeerConnection*)peerConnection gotICECandidate:(RTCICECandidate*)candidate方法:

- (void)peerConnection:(RTCPeerConnection*)peerConnection gotICECandidate:(RTCICECandidate*)candidate
{
ZUSLOG(@"gotICECandidate,peerConnection=%@,canidate=%@",peerConnection,candidate);
        NSDictionary *dicCandidate = @{
                                       @"type" : @"candidate",
                                       @"label" : @(candidate.sdpMLineIndex),
                                       @"id" : candidate.sdpMid,
                                       @"candidate" : candidate.sdp
                                       };
        NSString *message = [NSString stringWithDictionary:dicCandidate];
        # 将获取到ICECandidate通过socket服务器发送给其他客户端。
        [self sendRTCMessage:message withOfferType:NO];
}

而当其他端收到发送过来的ICECandidate,需要存入peerConnection备用:

    NSString *type = dict[@"type"];
    if ([type isEqualToString:@"candidate"]) {
        NSString* mid = MessageDict[@"id"];
        NSNumber* sdpLineIndex = MessageDict[@"label"];
        NSString* sdp = MessageDict[@"candidate"];
        
        //added by wafer for connection information,2017.06.15
        _sdpCandidate = [NSString stringWithFormat:@"%@%@\r\n",_sdpCandidate,sdp];
        
        RTCICECandidate* candidate = [[RTCICECandidate alloc] initWithMid:mid index:sdpLineIndex.intValue sdp:sdp];
         #添加到peerConnection里
          if (self.peerConnection) {
              [self.peerConnection addICECandidate:candidate];
                 ZUSLOG(@"receiveRTCMessage,addICECandidate");
            }
    }

到这里,通信之前的准备工作就差不多了,接下来要开始拨打电话了:
呼叫方首先生成一个offer类型的SDP(会话描述):

        #判断是否是呼叫方
      if (self.initiator) {   
                 #呼叫方生成一个offer类型的SDP
        [self.peerConnection createOfferWithDelegate:self constraints:self.sdpMediaConstraints];
      }

这里又出现了delegate,于是我们需要在回调方法里处理事件。
这里的protocol一共有两个方法:
1、生成SDP的回调:
- (void)peerConnection:(RTCPeerConnection *)peerConnection didCreateSessionDescription:(RTCSessionDescription *)sdp error:(NSError *)error;
2、这个是设置本地或者远程sdp的时候会调用:
- (void)peerConnection:(RTCPeerConnection *)peerConnection didSetSessionDescriptionWithError:(NSError *)error;
我们先处理第一个方法:
首先我们在成功生成SDP后,

- (void)peerConnection:(RTCPeerConnection*)peerConnection didCreateSessionDescription:(RTCSessionDescription*)origSdp error:(NSError*)error
{
    ZUSLOG(@"didCreateSessionDescription,peerConnection=%@,origSdp=%@,error=%@",peerConnection,origSdp,error);
        if (error) {  #生成失败
            return;
        }
        #(不管是呼叫方还是接收方,处理都是一样的)
        self.localSdp = [[RTCSessionDescription alloc] initWithType:origSdp.type sdp:[NSString preferVoiceCodec:origSdp.description voiceCodecType:self.voiceCodecType]];
        if (self.peerConnection) {
           # 生成成功就把他设为本地SDP
            [self.peerConnection setLocalDescriptionWithDelegate:self sessionDescription:self.localSdp];
        
        }
        # 然后再把生成的SDP发出去
        NSDictionary *dicSdp = @{@"type":self.localSdp.type, @"sdp":self.localSdp.description};
        NSString *message = [NSString stringWithDictionary:dicSdp];
        [self sendRTCMessage:message withOfferType:YES];
    });
}

然后就是接收方的处理(呼叫的信息是通过socket服务器告知的):
接收方在收到呼叫方的offer类型的SDP后,需要设置RemoteDescription为对方的SDP:

 if ([type isEqualToString:@"offer"] ) {
        NSString *sdpString = MessageDict[@"sdp"];
        self.remoteSdp = [[RTCSessionDescription alloc] initWithType:type sdp:[NSString preferVoiceCodec:sdpString voiceCodecType:self.voiceCodecType]];
            设置RemoteDescription为对方的SDP
            if (self.peerConnection) {
                [self.peerConnection setRemoteDescriptionWithDelegate:self
                                                   sessionDescription:self.remoteSdp];
        }

设置成功之后会触发代理方法:
- (void)peerConnection:(RTCPeerConnection *)peerConnection didSetSessionDescriptionWithError:(NSError *)error;
我们处理接收方设置完成之后的回调,接收方需要生成类型为answer的SDP返回给呼叫方,表示同意接受通信。

- (void)peerConnection:(RTCPeerConnection*)peerConnection didSetSessionDescriptionWithError:(NSError*)error
{
        if (error) {
            return;
        }
         #判断是接收方
        if (!self.initiator) { 
            if (self.peerConnection && self.peerConnection.remoteDescription && !self.peerConnection.localDescription) {
          #
                [self.peerConnection createAnswerWithDelegate:self constraints:self.sdpMediaConstraints];
            } 
        } 
}

然后又触发delegate方法
- (void)peerConnection:(RTCPeerConnection *)peerConnection didCreateSessionDescription:(RTCSessionDescription *)sdp error:(NSError *)error;
还是一模一样的,把生成的answer的SDP设为接收方自己的SDP,再把这个SDP再返回给呼叫方。

最后再回到接收方
接收方在收到回调之后,再把RemoteDescription设置好,至此,连接正式建立

if ([type isEqualToString:@"answer"]) {
        NSString *sdpString = MessageDict[@"sdp"];
        self.remoteSdp = [[RTCSessionDescription alloc] initWithType:type sdp:[NSString preferVoiceCodec:sdpString voiceCodecType:self.voiceCodecType]];
            if (self.peerConnection) {
                [self.peerConnection setRemoteDescriptionWithDelegate:self
                                                   sessionDescription:self.remoteSdp];
            } 
    }

从代码的角度看,呼叫方和接收方的逻辑公用还有回调之间的跳来跳去是有点晕。

但是总结一下:其实就是呼叫方生成offer的SDP,接收方生成answer的SDP,双方交换,然后设置好两端的localSDP和RemoteSDP。

最后,视频流传输的过程中会触发回调方法,记得渲染到远端视频界面remoteVideoView:

- (void)peerConnection:(RTCPeerConnection*)peerConnection addedStream:(RTCMediaStream*)stream
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ZUSLOG(@"PCO onAddStream.");
        
        if (self.supportVideo && stream.videoTracks.count) {
            self.remoteVideoTrack = stream.videoTracks[0];
            [self.remoteVideoTrack addRenderer:self.remoteVideoView];   //渲染
        }
    });
}

完 ~

上一篇下一篇

猜你喜欢

热点阅读