javascript – 如何在Chrome中为WebRTC调用者设置远程描述而不出错?

我希望逻辑上没有缺陷.

第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: Failed to execute ‘setRemoteDescription’ on
‘RTCPeerConnection’: Failed to set remote offer sdp: Called in wrong
state: kHaveLocalOffer

DOMException: Failed to execute ‘addIceCandidate’ on
‘RTCPeerConnection’: Error processing ICE candidate

试图调试但没有发现逻辑或代码中的任何缺陷.注意到pc对象具有localDescription和currentLocalDescription的一个奇怪的事情,我认为创建答案的被调用者必须同时具有要回答的描述类型,而是显示要提供的localDescription并且currentLocalDescription类型是应答.

javascript  – 如何在Chrome中为WebRTC调用者设置远程描述而不出错?
我不知道它是否应该表现得像那样,因为我是乞丐.

提前致谢.

解决方法:

你的代码是正确的.这是一个长期存在的bug in Chrome,需要进行协商.

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

在Firefox中,它可以工作.提议者协商一次,因为您一次添加两个曲目(视频/音频):

negotiating in stable
onmessage answer

并且,在回答者方面,您添加到“稳定”状态之外的曲目会添加到答案中:

onmessage offer
adding audio track
adding video track

但是在Chrome中,它被打破了,在提供者上需要两次解雇,每个轨道添加一次:

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

并且在回答者方面需要两次解雇,这甚至不是“稳定”状态:

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的两个部分:

>“排队任务”来解雇此事件. “在一次性对连接进行多次修改的常见情况下,排队可以防止提前进行协商.”
>如果连接的信令状态不是“稳定”,则中止这些步骤[触发事件].

解决方法

解决这两个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;
  }
}
上一篇:SDP 消息格式


下一篇:webrtc笔记(2): 1对1实时视频/语音通讯原理概述