feat: Dynamically fetch TURN credentials, improve WebRTC connection stability with ICE restart logic, and configure TURN via environment variables.

This commit is contained in:
2026-02-23 05:55:25 +01:00
parent deab4dd4a0
commit 26decc2c3c
4 changed files with 90 additions and 15 deletions

View File

@@ -25,12 +25,24 @@ let selectedVideoSourceId = null;
// Chart.js instance tracking
let bitrateChart = null;
const config = {
iceServers: [
{ urls: "stun:localhost:3478" },
{ urls: "turn:localhost:3478", username: "myuser", credential: "mypassword" }
]
};
// Build ICE config dynamically based on server URL
function getIceConfig(serverUrl, turnUser = 'myuser', turnPass = 'mypassword') {
let turnHost = 'localhost';
try {
const url = new URL(serverUrl);
turnHost = url.hostname;
} catch (e) {}
return {
iceServers: [
{ urls: `stun:${turnHost}:3478` },
{ urls: `turn:${turnHost}:3478`, username: turnUser, credential: turnPass }
],
iceCandidatePoolSize: 5
};
}
let config = getIceConfig('http://localhost:3000');
// 1. Get Desktop Sources / Switch Video Source Mid-Stream
getSourcesBtn.addEventListener('click', async () => {
@@ -315,6 +327,16 @@ startBtn.addEventListener('click', async () => {
});
function connectAndBroadcast(url, password) {
// Fetch TURN credentials from the server, then update ICE config
fetch(new URL('/turn-config', url).href)
.then(r => r.json())
.then(turn => {
config = getIceConfig(url, turn.username, turn.credential);
})
.catch(() => {
config = getIceConfig(url); // fallback to defaults
});
socket = io(url);
socket.on('connect', () => {
@@ -355,6 +377,20 @@ function connectAndBroadcast(url, password) {
}
};
// Monitor ICE state for stability
peerConnection.oniceconnectionstatechange = () => {
console.log(`Viewer ${id} ICE state:`, peerConnection.iceConnectionState);
if (peerConnection.iceConnectionState === 'failed') {
peerConnection.restartIce();
} else if (peerConnection.iceConnectionState === 'disconnected') {
setTimeout(() => {
if (peerConnections[id] && peerConnections[id].iceConnectionState === 'disconnected') {
peerConnections[id].restartIce();
}
}, 3000);
}
};
peerConnection.createOffer().then(sdp => {
if (window.RTCRtpSender && window.RTCRtpSender.getCapabilities) {
const caps = window.RTCRtpSender.getCapabilities('video');