如何在Chrome中为WebRTC调用者设置远程描述而没有错误?

时间:2018-10-28 08:36:04

标签: javascript webrtc sdp peer-connection rtcpeerconnection

我希望逻辑上没有缺陷。

第1步:呼叫者创建报价

步骤2:呼叫者设置了localDescription

步骤3:呼叫者将描述发送给被呼叫者

// --------------------------------------------- --------- //

第4步:被叫方收到要约集的远程描述

步骤5:被叫方创建答案

步骤6:被叫方设置本地描述

第7步:被叫方将说明发送给主叫方

// --------------------------------------------- --------- //

步骤8:呼叫者收到答案并设置远程描述

这是上面的代码

const socket = io();
const constraints = {
  audio: true,
  video: true
};
const configuration = {
  iceServers: [{
    "url": "stun:23.21.150.121"
  }, {
    "url": "stun:stun.l.google.com:19302"
  }]
};

const selfView = $('#selfView')[0];
const remoteView = $('#remoteView')[0];

var pc = new RTCPeerConnection(configuration);

pc.onicecandidate = ({
  candidate
}) => {
  socket.emit('message', {
    to: $('#remote').val(),
    candidate: candidate
  });
};

pc.onnegotiationneeded = async () => {
  try {
    await pc.setLocalDescription(await pc.createOffer());
    socket.emit('message', {
      to: $('#remote').val(),
      desc: pc.localDescription
    });
  } catch (err) {
    console.error(err);
  }
};

pc.ontrack = (event) => {
  // don't set srcObject again if it is already set.
  if (remoteView.srcObject) return;
  remoteView.srcObject = event.streams[0];
};

socket.on('message', async ({
  from,
  desc,
  candidate
}) => {
  $('#remote').val(from);
  try {
    if (desc) {
      // if we get an offer, we need to reply with an answer
      if (desc.type === 'offer') {
        await pc.setRemoteDescription(desc);
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        stream.getTracks().forEach((track) => pc.addTrack(track, stream));
        selfView.srcObject = stream;
        await pc.setLocalDescription(await pc.createAnswer());
        console.log(pc.localDescription);
        socket.emit({
          to: from,
          desc: pc.localDescription
        });
      } else if (desc.type === 'answer') {
        await pc.setRemoteDescription(desc).catch(err => console.log(err));
      } else {
        console.log('Unsupported SDP type.');
      }
    } else if (candidate) {
      await pc.addIceCandidate(new RTCIceCandidate(candidate)).catch(err => console.log(err));
    }
  } catch (err) {
    console.error(err);
  }
});


async function start() {
  try {
    // get local stream, show it in self-view and add it to be sent
    const stream = await requestUserMedia(constraints);
    stream.getTracks().forEach((track) => pc.addTrack(track, stream));
    attachMediaStream(selfView, stream);
  } catch (err) {
    console.error(err);
  }
}

socket.on('id', (data) => {
  $('#myid').text(data.id);
});


// this function is called once the caller hits connect after inserting the unique id of the callee
async function connect() {
  try {
    await pc.setLocalDescription(await pc.createOffer());
    socket.emit('message', {
      to: $('#remote').val(),
      desc: pc.localDescription
    });
  } catch (err) {
    console.error(err);
  }
}

socket.on('error', data => {
  console.log(data);
});

现在,此代码在执行第8步

时会引发错误
  

DOMException:无法在以下位置执行“ setRemoteDescription”   'RTCPeerConnection':无法设置远程商品sdp:调用错误   状态:kHaveLocalOffer

     

DOMException:无法在上执行“ addIceCandidate”   'RTCPeerConnection':处理ICE候选者时出错

试图进行调试,但在逻辑或代码中未发现任何缺陷。注意到pc对象具有localDescriptioncurrentLocalDescription这件事很奇怪,我认为创建答案的被叫方必须同时将描述类型都设为answer,但显示localDescriptionoffercurrentLocalDescription类型为answer

enter image description here 我不知道它是否应该像我开始时那样表现。

谢谢。

1 个答案:

答案 0 :(得分:4)

您的代码正确。这是bug in Chromenegotiationneeded的长期合作。

我已经在a fiddle中对其进行了检测(右键单击并在两个相邻的窗口中打开,然后单击其中的一个)。

在Firefox中有效。要约人协商一次,因为您一次添加了两个轨道(视频/音频):

negotiating in stable
onmessage answer

,在答录器端,您在'stable'状态之外添加的曲目将添加到答案:

onmessage offer
adding audio track
adding video track

但是在Chrome中,它坏了,在要约上触发negotiationneeded两次,每添加一条轨道一次:

negotiating in stable
negotiating in stable
onmessage offer
DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection':
  Failed to set remote offer sdp: Called in wrong state: kHaveLocalOffer
onmessage offer
DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection':
  Failed to set remote offer sdp: Called in wrong state: kHaveLocalOffer
onmessage offer
DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection':
  Failed to set remote offer sdp: Called in wrong state: kHaveLocalOffer

并在答录器端两次触发negotiationneeded,甚至没有进入'stable'状态:

onmessage offer
adding audio track
adding video track
negotiating in have-remote-offer
negotiating in have-remote-offer
onmessage offer
DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection':
  Failed to set remote offer sdp: Called in wrong state: kHaveLocalOffer

这些额外的事件造成了在此处两端都看到的相互状态错误的破坏。

具体来说,Chrome违反了spec的两个部分:

  1. “排队任务” 触发此事件。 “在通常要同时对连接进行多次修改的常见情况下,排队可以防止协商过早触发。”

  2. 如果连接的信令状态不是"stable",请中止这些步骤[以触发事件]。

解决方法

要同时解决这两个Chrome错误(为了简便起见,请使用async / await

let negotiating = false;
pc.onnegotiationneeded = async e => {
  try {
    if (negotiating || pc.signalingState != "stable") return;
    negotiating = true;
    /* Your async/await-using code goes here */
  } finally {
    negotiating = false;
  }
}