WebRTC: коннект больше 2 пользователей
Пытаюсь написать приложение WebRTC, используя socket.io.
Signalling server написан на питоне
import socketio
import uvicorn
from starlette.applications import Starlette
ROOM = 'room'
sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
star_app = Starlette(debug=True)
app = socketio.ASGIApp(sio, star_app)
@sio.event
async def connect(sid, environ):
await sio.emit('ready', room=ROOM, skip_sid=sid)
sio.enter_room(sid, ROOM)
@sio.event
async def data(sid, data):
await sio.emit('data', data, room=ROOM, skip_sid=sid)
@sio.event
async def disconnect(sid):
sio.leave_room(sid, ROOM)
if __name__ == '__main__':
uvicorn.run(app, host='0.0.0.0', port=8003)
Код клиета
<script>
const SIGNALING_SERVER_URL = 'http://127.0.0.1:8003?session_id=1';
// WebRTC config: you don't have to change this for the example to work
// If you are testing on localhost, you can just use PC_CONFIG = {}
const PC_CONFIG = {};
// Signaling methods
let socket = io(SIGNALING_SERVER_URL, {autoConnect: false});
socket.on('data', (data) => {
console.log('Data received: ', data);
handleSignalingData(data);
});
socket.on('ready', () => {
console.log('Ready');
// Connection with signaling server is ready, and so is local stream
createPeerConnection();
sendOffer();
});
let sendData = (data) => {
socket.emit('data', data);
};
// WebRTC methods
let pc;
let localStream;
let remoteStreamElement = document.querySelector('#remoteStream');
let getLocalStream = () => {
navigator.mediaDevices.getUserMedia({audio: true, video: true})
.then((stream) => {
console.log('Stream found');
localStream = stream;
// Connect after making sure that local stream is availble
socket.connect();
})
.catch(error => {
console.error('Stream not found: ', error);
});
}
let createPeerConnection = () => {
try {
pc = new RTCPeerConnection(PC_CONFIG);
pc.onicecandidate = onIceCandidate;
pc.onaddstream = onAddStream;
pc.addStream(localStream);
console.log('PeerConnection created');
} catch (error) {
console.error('PeerConnection failed: ', error);
}
};
let sendOffer = () => {
console.log('Send offer');
pc.createOffer().then(
setAndSendLocalDescription,
(error) => {
console.error('Send offer failed: ', error);
}
);
};
let sendAnswer = () => {
console.log('Send answer');
pc.createAnswer().then(
setAndSendLocalDescription,
(error) => {
console.error('Send answer failed: ', error);
}
);
};
let setAndSendLocalDescription = (sessionDescription) => {
pc.setLocalDescription(sessionDescription);
console.log('Local description set');
sendData(sessionDescription);
};
let onIceCandidate = (event) => {
if (event.candidate) {
console.log('ICE candidate');
sendData({
type: 'candidate',
candidate: event.candidate
});
}
};
let onAddStream = (event) => {
console.log('Add stream');
remoteStreamElement.srcObject = event.stream;
};
let handleSignalingData = (data) => {
// let msg = JSON.parse(data);
switch (data.type) {
case 'offer':
createPeerConnection();
pc.setRemoteDescription(new RTCSessionDescription(data));
sendAnswer();
break;
case 'answer':
pc.setRemoteDescription(new RTCSessionDescription(data));
break;
case 'candidate':
pc.addIceCandidate(new RTCIceCandidate(data.candidate));
break;
}
};
// Start connection
getLocalStream();
</script>
Также использую socket.io библиотеку
https://github.com/socketio/socket.io/blob/master/client-dist/socket.io.js
Когда два человека в коннекте - все отлично работает. Но как только к ним пытается подключиться третий пользователь, стриминг останавливается с ошибкой
Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable
Ошибка эта прослеживается во всех браузерах.
Репозиторий с докером:
https://github.com/pfertyk/webrtc-working-example
Инструкция:
https://pfertyk.me/2020/03/webrtc-a-working-example/
Ответы (1 шт):
'use strict';
const startButton = document.getElementById('startButton');
const callButton1 = document.getElementById('callButton1');
const callButton2 = document.getElementById('callButton2');
const hangupButton = document.getElementById('hangupButton');
callButton1.disabled = true;
callButton2.disabled = true;
hangupButton.disabled = true;
startButton.onclick = start;
callButton1.onclick = callTwo;
callButton2.onclick = callAttach;
hangupButton.onclick = hangup;
const offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
const servers = null;
console.log = () => {}
function gotStream(stream) {
console.log('Получаем локальный стрим с камеры');
document.querySelector('video#video1').srcObject = stream;
window.localStream = stream;
callButton1.disabled = false;
}
function start() {
console.log('Запрос на получение локального стрима с камеры');
startButton.disabled = true;
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(gotStream)
.catch(e => console.log('getUserMedia() error: ', e));
}
class PeerConnection {
constructor(videoElement){
this.videoElement = videoElement;
this.pcLocal = new RTCPeerConnection(servers);
this.pcRemote = new RTCPeerConnection(servers);
this.pcRemote.ontrack = this.gotRemoteStream;
this.pcLocal.onicecandidate = this.iceCallbackLocal;
this.pcRemote.onicecandidate = this.iceCallbackRemote;
// создаем оффер для подключения
window.localStream.getTracks().forEach(track => this.pcLocal.addTrack(track, window.localStream));
this.pcLocal
.createOffer(offerOptions)
.then(this.gotDescriptionLocal, onCreateSessionDescriptionError);
}
gotDescriptionLocal = (desc) => {
this.pcLocal.setLocalDescription(desc);
console.log(`Установили локальное описание\n${desc.sdp}`);
this.pcRemote.setRemoteDescription(desc);
// отсылаем одобрение на получение видео
this.pcRemote.createAnswer().then(this.gotDescriptionRemote, onCreateSessionDescriptionError);
}
gotDescriptionRemote = (desc) => {
this.pcRemote.setLocalDescription(desc);
console.log(`Получили ответ с удаленного соединения\n${desc.sdp}`);
this.pcLocal.setRemoteDescription(desc);
}
gotRemoteStream = (e) => {
if (this.videoElement.srcObject !== e.streams[0]) {
this.videoElement.srcObject = e.streams[0];
console.log('pc: получаем и отображаем удаленный стрим');
}
}
iceCallbackLocal = (event) => {
if (event.candidate){
handleCandidate(event.candidate, this.pcRemote, 'pc: ', 'локальный кандидат на удаленном соединении');
}
}
iceCallbackRemote = (event) => {
if (event.candidate){
handleCandidate(event.candidate, this.pcLocal, 'pc: ', 'удаленный кандидат на локальном соединении');
}
}
close(){
// закрываем соединения
this.pcLocal.close();
this.pcRemote.close();
this.pcLocal = this.pcRemote = null;
}
}
// два удаленных соединения (соединение локальное + удалленое)
let pc1 = null;
let pc2 = null;
function callTwo() {
callButton1.disabled = true;
callButton2.disabled = false;
hangupButton.disabled = false;
console.log('Начало звонка');
const audioTracks = window.localStream.getAudioTracks();
const videoTracks = window.localStream.getVideoTracks();
if (audioTracks.length > 0) {
console.log(`Используется аудио устройство: ${audioTracks[0].label}`);
}
if (videoTracks.length > 0) {
console.log(`Используется видео устройство: ${videoTracks[0].label}`);
}
// инициализация участников
pc1 = new PeerConnection(document.querySelector('video#video2'))
//pc2 = new PeerConnection(document.querySelector('video#video3'))
}
function callAttach() {
callButton2.disabled = true;
pc2 = new PeerConnection(document.querySelector('video#video3'))
}
// положить трубку
function hangup() {
console.log('Ending calls');
pc1.close();
pc2.close();
hangupButton.disabled = true;
callButton1.disabled = false;
}
// добавление кандидатов к соединению
function handleCandidate(candidate, dest, prefix, type) {
dest.addIceCandidate(candidate)
.then(onAddIceCandidateSuccess, onAddIceCandidateError);
console.log(`${prefix}New ${type} ICE candidate: ${candidate ? candidate.candidate : '(null)'}`);
}
// обработчик успешного добавления участника
function onAddIceCandidateSuccess() {
console.log('AddIceCandidate success.');
}
// обработчик ошибки добавления участника
function onAddIceCandidateError(error) {
console.log(`Failed to add ICE candidate: ${error.toString()}`);
}
// обработчик ошибки создания описания
function onCreateSessionDescriptionError(error) {
console.log(`Failed to create session description: ${error.toString()}`);
}
video {
width: 150px;
height: 100px;
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="container">
<video id="video1" playsinline autoplay muted></video>
<video id="video2" playsinline autoplay></video>
<video id="video3" playsinline autoplay></video>
<div>
<button id="startButton">Получить стрим</button>
<button id="callButton1">Соединение 2х</button>
<button id="callButton2">Подключение 1го</button>
<button id="hangupButton">Завершить</button>
</div>
</div>
</body>
</html>
Небольшой пример кода демонстрирующий соединение 2 узлов при последующем подсоединении третьего узла, к сожалению тут это не работает, поэтому ссылка на песочницу в данном примере трансляция идет только с первого узла.
Коментарии присутствуют в коде, но приложу небольшое объяснение. Мы здесь не используем ни STUN ни TURN серверы для передачи данных, все что можно и нужно работает однако пересылка стрима осуществляется через глобальную переменну что при наличие сокет соединения легко переделать. Каждое соединение хранит 2 узла локальный и удаленный и между ними собственно и создается связь поэтому не происходит никаких конфликтов (два узла - одна связь) Создаем офер, тут же отправляем ответ, подключаем кандидатов в оба конца и связь налажена.
Рекомендую учебник на русском так как в сети не так уж и много информации на этот счет и большинство на английском.