feat: Dynamically fetch TURN credentials, improve WebRTC connection stability with ICE restart logic, and configure TURN via environment variables.
This commit is contained in:
@@ -3,17 +3,30 @@ const remoteVideo = document.getElementById('remoteVideo');
|
||||
const overlay = document.getElementById('overlay');
|
||||
|
||||
let peerConnection;
|
||||
const config = {
|
||||
|
||||
// Fetch TURN credentials dynamically from the server
|
||||
const turnHost = window.location.hostname;
|
||||
let config = {
|
||||
iceServers: [
|
||||
{ urls: "stun:localhost:3478" },
|
||||
{
|
||||
urls: "turn:localhost:3478",
|
||||
username: "myuser",
|
||||
credential: "mypassword"
|
||||
}
|
||||
]
|
||||
{ urls: `stun:${turnHost}:3478` }
|
||||
],
|
||||
iceCandidatePoolSize: 5
|
||||
};
|
||||
|
||||
// Load TURN credentials before any connections
|
||||
fetch('/turn-config')
|
||||
.then(r => r.json())
|
||||
.then(turn => {
|
||||
config = {
|
||||
iceServers: [
|
||||
{ urls: `stun:${turnHost}:3478` },
|
||||
{ urls: `turn:${turnHost}:3478`, username: turn.username, credential: turn.credential }
|
||||
],
|
||||
iceCandidatePoolSize: 5
|
||||
};
|
||||
})
|
||||
.catch(e => console.error('Failed to load TURN config:', e));
|
||||
|
||||
socket.on('offer', (id, description) => {
|
||||
// Close any existing connection before creating a new one
|
||||
if (peerConnection) {
|
||||
@@ -31,10 +44,27 @@ socket.on('offer', (id, description) => {
|
||||
// Auto-unmute when the user interacts with the document to bypass browser autoplay restrictions
|
||||
document.addEventListener('click', () => {
|
||||
remoteVideo.muted = false;
|
||||
// Set sink to max possible volume explicitly avoiding browser gain staging
|
||||
remoteVideo.volume = 1.0;
|
||||
}, {once: true});
|
||||
|
||||
// Monitor ICE connection state for stability
|
||||
peerConnection.oniceconnectionstatechange = () => {
|
||||
console.log('ICE state:', peerConnection.iceConnectionState);
|
||||
if (peerConnection.iceConnectionState === 'failed') {
|
||||
// Try ICE restart before giving up
|
||||
console.log('ICE failed, attempting restart...');
|
||||
peerConnection.restartIce();
|
||||
} else if (peerConnection.iceConnectionState === 'disconnected') {
|
||||
// Wait briefly then check if it recovered
|
||||
setTimeout(() => {
|
||||
if (peerConnection && peerConnection.iceConnectionState === 'disconnected') {
|
||||
console.log('ICE still disconnected, attempting restart...');
|
||||
peerConnection.restartIce();
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
peerConnection.onicecandidate = event => {
|
||||
if (event.candidate) {
|
||||
socket.emit('candidate', id, event.candidate);
|
||||
|
||||
Reference in New Issue
Block a user