WebRTC創建鏈接過程介紹

概述

由於最近在作WebRTC相關的項目,爲了對WebRTC創建鏈接和傳輸有更深刻的瞭解,仍是寫一篇文章介紹一下。最開始是從WebRTC的官方文檔入手,固然還有裏面的samples。由於通訊的過程尚未涉及到,先從鏈接過程作切入。javascript

SDP

SDP是Session Description Protocol,從文檔裏面能夠看到,是p2p鏈接的標準協議,裏面包括了codec、地址和音視頻的時間信息。這裏面SDP不是通訊協議,通訊協議通常是RTP或者SRTP(安全的RTP),可是通常都會須要SDP來先進行鏈接創建。java

Session description

session是都過一行一個field的方式來描述的,格式是:安全

<character>=<value>

其中<character>是一個大小寫敏感的字母,<value>是一個結構化的字符串,一般是utf-8編碼的,等號後面不能直接跟空格。
SDP消息裏面有3個主要的塊,session, timingmedia描述。每一個消息都包含了多個timingmedia描述。每一行field順序是固定的,*=表明是可選的,每一個含義以下:session

**Session description**
    v=  (protocol version number, currently only 0)
    o=  (originator and session identifier : username, id, version number, network address)
    s=  (session name : mandatory with at least one UTF-8-encoded character)
    i=\* (session title or short information)
    u=\* (URI of description)
    e=\* (zero or more email address with optional name of contacts)
    p=\* (zero or more phone number with optional name of contacts)
    c=\* (connection information—not required if included in all media)
    b=\* (zero or more bandwidth information lines)
    _One or more **Time descriptions** ("t=" and "r=" lines; see below)_
    z=\* (time zone adjustments)
    k=\* (encryption key)
    a=\* (zero or more session attribute lines)
    _Zero or more **Media descriptions** (each one starting by an "m=" line; see below)_
**Time description** (mandatory)
    t=  (time the session is active)
    r=\* (zero or more repeat times)
**Media description** (if present)
    m=  (media name and transport address)
    i=\* (media title or information field)
    c=\* (connection information — optional if included at session level)
    b=\* (zero or more bandwidth information lines)
    k=\* (encryption key)
    a=\* (zero or more media attribute lines — overriding the Session attribute lines)

一個常見的SDP消息是這樣的:ide

v=0
   o=alice 2890844526 2890844526 IN IP4 host.anywhere.com
   s=
   c=IN IP4 host.anywhere.com
   t=0 0
   m=audio 49170 RTP/AVP 0
   a=rtpmap:0 PCMU/8000
   m=video 51372 RTP/AVP 31
   a=rtpmap:31 H261/90000
   m=video 53000 RTP/AVP 32
   a=rtpmap:32 MPV/90000

RTCPeerConnection

全部鏈接都是從RTCPeerConnection這個對象開始,他繼承自EventTarget,擁有一些增長事件監聽的能力。ui

Caller 打電話者(推流方pc1)

  • 建立RTCPeerConnection對象,以及準備須要推的Stream對象
pc1 = new RTCPeerConnection(servers);
localStream.getTracks().forEach((track) => {
  pc1.addTrack(track, localStream);
});
  • 建立一個Offer,並設置爲本身的LocalDescription
const offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};
const offer = await pc1.createOffer(offerOptions);
pc1.setLocalDescription(offer);
  • 拿到pc2的Anwser,並設置爲本身的RemoteDescription
pc1.setRemoteDescription(answer);

Callee 接電話者(播放方pc2)

  • 拿到pc1的Offer,設置爲本身的RemoteDescription
pc2.setLocalDescription(desc);
  • 建立一個Anwser,設置爲本身的LocalDescription
const answer =pc2.createAnswer();
pc2.setLocalDescription(answer);
相關文章
相關標籤/搜索