highest quality

This commit is contained in:
Joey Eamigh 2025-12-10 21:15:04 -05:00
parent 421b633045
commit a1c9798215
No known key found for this signature in database
GPG Key ID: CE8C05DFFC53C9CB
6 changed files with 1351 additions and 872 deletions

View File

@ -15,4 +15,4 @@
"express": "^5.2.1", "express": "^5.2.1",
"socket.io": "^4.8.1" "socket.io": "^4.8.1"
} }
} }

View File

@ -6,6 +6,8 @@ const streamListUl = document.getElementById('streamList');
const lobbyView = document.getElementById('lobby-view'); const lobbyView = document.getElementById('lobby-view');
const streamView = document.getElementById('stream-view'); const streamView = document.getElementById('stream-view');
const streamTitle = document.getElementById('currentStreamTitle'); const streamTitle = document.getElementById('currentStreamTitle');
const upstreamMetricsBox = document.getElementById('upstreamMetrics');
const downstreamMetricsBox = document.getElementById('downstreamMetrics');
// --- Global State --- // --- Global State ---
let localStream = null; let localStream = null;
@ -15,20 +17,39 @@ let iceServers = [];
let currentUpstreamPC = null; let currentUpstreamPC = null;
let currentDownstreamPC = null; let currentDownstreamPC = null;
let downstreamId = null; let downstreamId = null;
let origVideoStream,
displayedVideoStream,
sentVideoStream,
origAudioStream,
displayedAudioStream,
sentAudioStream,
origVideoTrack,
origAudioTrack,
displayedVideoTrack,
displayedAudioTrack,
sentVideoTrack,
sentAudioTrack;
// FADING connections // FADING connections
let oldUpstreamPCs = []; let oldUpstreamPCs = [];
let oldDownstreamPCs = []; let oldDownstreamPCs = [];
// Debug metrics history for bitrate/fps deltas
const metricsHistory = {
upstream: null,
downstream: null,
};
// --- 1. Initialization --- // --- 1. Initialization ---
async function init() { async function init() {
try { try {
const response = await fetch('/api/get-turn-credentials'); const response = await fetch('/api/get-turn-credentials');
const data = await response.json(); const data = await response.json();
iceServers = data.iceServers; console.log('TURN data:', data);
} catch (e) { iceServers = data.iceServers;
iceServers = [{ urls: 'stun:stun.l.google.com:19302' }]; } catch (e) {
} iceServers = [{ urls: 'stun:stun.l.google.com:19302' }];
}
} }
init(); init();
@ -36,255 +57,541 @@ init();
// Receive list of streams from server // Receive list of streams from server
socket.on('stream_list_update', (streams) => { socket.on('stream_list_update', (streams) => {
streamListUl.innerHTML = ""; streamListUl.innerHTML = '';
if (streams.length === 0) { if (streams.length === 0) {
streamListUl.innerHTML = "<li style='cursor:default; color:#777;'>No active streams. Start one!</li>"; streamListUl.innerHTML = "<li style='cursor:default; color:#777;'>No active streams. Start one!</li>";
return; return;
} }
streams.forEach(name => { streams.forEach((name) => {
const li = document.createElement('li'); const li = document.createElement('li');
li.innerText = `${name}`; li.innerText = `${name}`;
li.onclick = () => joinStream(name); li.onclick = () => joinStream(name);
streamListUl.appendChild(li); streamListUl.appendChild(li);
}); });
}); });
async function startStream() { async function startStream() {
const name = document.getElementById('streamNameInput').value; const name = document.getElementById('streamNameInput').value;
const fileInput = document.getElementById('videoFileInput'); const fileInput = document.getElementById('videoFileInput');
const file = fileInput.files[0]; const file = fileInput.files[0];
if (!name) return alert("Please enter a name"); if (!name) return alert('Please enter a name');
try { try {
if (file) { if (file) {
// --- OPTION A: VIDEO FILE MODE --- // --- OPTION A: VIDEO FILE MODE ---
console.log("Starting stream from video file..."); console.log('Starting stream from video file...');
// 1. Create a URL for the local file // 1. Create a URL for the local file
const fileURL = URL.createObjectURL(file); const fileURL = URL.createObjectURL(file);
// 2. Set it to the local video element // 2. Set it to the local video element
localVideo.src = fileURL; localVideo.src = fileURL;
localVideo.loop = true; // <--- HERE IS THE LOOP LOGIC localVideo.loop = true; // <--- HERE IS THE LOOP LOGIC
localVideo.muted = false; // Must be unmuted to capture audio, use headphones! localVideo.muted = false; // Must be unmuted to capture audio, use headphones!
localVideo.volume = 1.0; localVideo.volume = 1.0;
// 3. Play the video (required before capturing) // 3. Play the video (required before capturing)
await localVideo.play(); await localVideo.play();
// 4. Capture the stream from the video element // 4. Capture the stream from the video element
// (Chrome/Edge use captureStream, Firefox uses mozCaptureStream) // (Chrome/Edge use captureStream, Firefox uses mozCaptureStream)
if (localVideo.captureStream) { if (localVideo.captureStream) {
localStream = localVideo.captureStream(); localStream = localVideo.captureStream();
} else if (localVideo.mozCaptureStream) { } else {
localStream = localVideo.mozCaptureStream(); return alert('Your browser does not support capturing video from files.');
} else { }
return alert("Your browser does not support capturing video from files.");
}
// Note: captureStream() sometimes doesn't capture audio if the element is muted. // Note: captureStream() sometimes doesn't capture audio if the element is muted.
// If you want to stream audio, you must hear it locally too. // If you want to stream audio, you must hear it locally too.
} else {
// --- OPTION B: WEBCAM MODE ---
console.log('Starting stream from Webcam...');
localStream = await navigator.mediaDevices.getUserMedia({
video: { width: { ideal: 4096 } },
audio: true,
});
localVideo.srcObject = localStream.clone();
localVideo.muted = true; // Mute local webcam to avoid feedback loop
}
} else { // --- COMMON LOGIC ---
// --- OPTION B: WEBCAM MODE ---
console.log("Starting stream from Webcam...");
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
localVideo.srcObject = localStream;
localVideo.muted = true; // Mute local webcam to avoid feedback loop
}
// --- COMMON LOGIC --- // UI Switch
lobbyView.style.display = 'none';
streamView.style.display = 'block';
remoteVideo.style.display = 'none'; // Broadcaster doesn't see remote
streamTitle.innerText = `Broadcasting: ${name}`;
// UI Switch socket.emit('start_stream', name);
lobbyView.style.display = 'none'; statusDiv.innerText = `Status: Broadcasting (Head) | ID: ${socket.id}`;
streamView.style.display = 'block'; } catch (err) {
remoteVideo.style.display = 'none'; // Broadcaster doesn't see remote console.error(err);
streamTitle.innerText = `Broadcasting: ${name}`; alert('Failed to start stream: ' + err.message);
}
socket.emit('start_stream', name);
statusDiv.innerText = `Status: Broadcasting (Head) | ID: ${socket.id}`;
} catch (err) {
console.error(err);
alert("Failed to start stream: " + err.message);
}
} }
function joinStream(name) { function joinStream(name) {
// UI Switch // UI Switch
lobbyView.style.display = 'none'; lobbyView.style.display = 'none';
streamView.style.display = 'block'; streamView.style.display = 'block';
localVideo.style.display = 'none'; // Viewers don't see themselves localVideo.style.display = 'none'; // Viewers don't see themselves
streamTitle.innerText = `Watching: ${name}`; streamTitle.innerText = `Watching: ${name}`;
socket.emit('join_stream', name); socket.emit('join_stream', name);
statusDiv.innerText = `Status: Joining chain... | ID: ${socket.id}`; statusDiv.innerText = `Status: Joining chain... | ID: ${socket.id}`;
} }
function leaveStream() { function leaveStream() {
location.reload(); // Simple way to reset state and go back to lobby location.reload(); // Simple way to reset state and go back to lobby
} }
// --- 3. Health Reporting (Unchanged) --- // --- 3. Health Reporting (Unchanged) ---
setInterval(calculateAndReportHealth, 5000); setInterval(calculateAndReportHealth, 5000);
setInterval(pollPeerMetrics, 2000);
async function calculateAndReportHealth() { async function calculateAndReportHealth() {
if (localStream) { if (localStream) {
socket.emit('update_score', 100); socket.emit('update_score', 100);
return; return;
} }
if (!currentUpstreamPC) return; if (!currentUpstreamPC) return;
try { try {
const stats = await currentUpstreamPC.getStats(); const stats = await currentUpstreamPC.getStats();
let packetsLost = 0; let packetsLost = 0;
let packetsReceived = 0; let packetsReceived = 0;
let jitter = 0; let jitter = 0;
stats.forEach(report => { stats.forEach((report) => {
if (report.type === 'inbound-rtp' && report.kind === 'video') { if (report.type === 'inbound-rtp' && report.kind === 'video') {
packetsLost = report.packetsLost || 0; packetsLost = report.packetsLost || 0;
packetsReceived = report.packetsReceived || 0; packetsReceived = report.packetsReceived || 0;
jitter = report.jitter || 0; jitter = report.jitter || 0;
} }
}); });
const totalPackets = packetsReceived + packetsLost; const totalPackets = packetsReceived + packetsLost;
if (totalPackets === 0) return; if (totalPackets === 0) return;
const lossRate = packetsLost / totalPackets; const lossRate = packetsLost / totalPackets;
const score = 100 - (lossRate * 100 * 5) - (jitter * 100); const score = 100 - lossRate * 100 * 5 - jitter * 100;
const finalScore = Math.max(0, Math.min(100, score)); const finalScore = Math.max(0, Math.min(100, score));
console.log(`Health: ${finalScore.toFixed(0)} | Loss: ${(lossRate * 100).toFixed(2)}%`); console.log(`Health: ${finalScore.toFixed(0)} | Loss: ${(lossRate * 100).toFixed(2)}%`);
socket.emit('update_score', finalScore); socket.emit('update_score', finalScore);
} catch (e) { } } catch (e) {}
} }
// --- 4. Socket Events (Logic Updated for Smart Disconnect) --- // --- 4. Socket Events (Logic Updated for Smart Disconnect) ---
socket.on('connect_to_downstream', async ({ downstreamId: targetId }) => { socket.on('connect_to_downstream', async ({ downstreamId: targetId }) => {
downstreamId = targetId; downstreamId = targetId;
await setupDownstreamConnection(targetId); await setupDownstreamConnection(targetId);
}); });
socket.on('disconnect_downstream', () => { socket.on('disconnect_downstream', () => {
if (currentDownstreamPC) { if (currentDownstreamPC) {
currentDownstreamPC.close(); currentDownstreamPC.close();
currentDownstreamPC = null; currentDownstreamPC = null;
downstreamId = null; downstreamId = null;
} }
oldDownstreamPCs.forEach(pc => pc.close()); oldDownstreamPCs.forEach((pc) => pc.close());
oldDownstreamPCs = []; oldDownstreamPCs = [];
}); });
socket.on('signal_msg', async ({ sender, type, sdp, candidate }) => { socket.on('signal_msg', async ({ sender, type, sdp, candidate }) => {
if (type === 'offer') { if (type === 'offer') {
await handleUpstreamOffer(sender, sdp); await handleUpstreamOffer(sender, sdp);
} else if (type === 'answer') { } else if (type === 'answer') {
if (currentDownstreamPC && sender === downstreamId) { if (currentDownstreamPC && sender === downstreamId) {
await currentDownstreamPC.setRemoteDescription(new RTCSessionDescription(sdp)); await currentDownstreamPC.setRemoteDescription(new RTCSessionDescription(sdp));
} }
} else if (type === 'candidate') { } else if (type === 'candidate') {
const ice = new RTCIceCandidate(candidate); const ice = new RTCIceCandidate(candidate);
if (currentDownstreamPC && sender === downstreamId) currentDownstreamPC.addIceCandidate(ice).catch(e => { }); if (currentDownstreamPC && sender === downstreamId) currentDownstreamPC.addIceCandidate(ice).catch((e) => {});
if (currentUpstreamPC) currentUpstreamPC.addIceCandidate(ice).catch(e => { }); if (currentUpstreamPC) currentUpstreamPC.addIceCandidate(ice).catch((e) => {});
oldUpstreamPCs.forEach(pc => pc.addIceCandidate(ice).catch(e => { })); oldUpstreamPCs.forEach((pc) => pc.addIceCandidate(ice).catch((e) => {}));
oldDownstreamPCs.forEach(pc => pc.addIceCandidate(ice).catch(e => { })); oldDownstreamPCs.forEach((pc) => pc.addIceCandidate(ice).catch((e) => {}));
} }
}); });
socket.on('error_msg', (msg) => { socket.on('error_msg', (msg) => {
alert(msg); alert(msg);
location.reload(); location.reload();
}); });
socket.on('stream_ended', () => { socket.on('stream_ended', () => {
alert("Stream ended by host"); alert('Stream ended by host');
location.reload(); location.reload();
}); });
socket.on('request_keyframe', () => { socket.on('request_keyframe', () => {
console.log("Network requested keyframe"); console.log('Network requested keyframe');
// If we were using Insertable streams, we'd need to handle this. // If we were using Insertable streams, we'd need to handle this.
// With Standard API, the browser handles PLI automatically. // With Standard API, the browser handles PLI automatically.
}); });
// --- 5. WebRTC Logic (Merged Smart Disconnect) --- // --- 5. WebRTC Logic (Merged Smart Disconnect) ---
async function handleUpstreamOffer(senderId, sdp) { async function handleUpstreamOffer(senderId, sdp) {
const newPC = new RTCPeerConnection({ iceServers }); const newPC = new RTCPeerConnection({ iceServers });
// Safety: If connection hangs, kill old one eventually // Safety: If connection hangs, kill old one eventually
let safetyTimer = setTimeout(() => { let safetyTimer = setTimeout(() => {
if (currentUpstreamPC && currentUpstreamPC !== newPC) { if (currentUpstreamPC && currentUpstreamPC !== newPC) {
currentUpstreamPC.close(); currentUpstreamPC.close();
} }
}, 15000); }, 15000);
newPC.ontrack = (event) => { newPC.ontrack = async (event) => {
clearTimeout(safetyTimer); // Success! console.log('Received track from upstream:', event);
clearTimeout(safetyTimer); // Success!
remoteVideo.srcObject = event.streams[0]; if (event.track.kind === 'video') {
statusDiv.innerText = `Status: Connected | ID: ${socket.id}`; origVideoStream = event.streams[0];
displayedVideoStream = origVideoStream.clone();
sentVideoStream = origVideoStream.clone();
if (currentDownstreamPC) { origVideoTrack = event.track;
const sender = currentDownstreamPC.getSenders().find(s => s.track && s.track.kind === event.track.kind); displayedVideoTrack = origVideoTrack.clone();
if (sender) sender.replaceTrack(event.track); sentVideoTrack = origVideoTrack.clone();
} } else if (event.track.kind === 'audio') {
origAudioStream = event.streams[0];
displayedAudioStream = origAudioStream.clone();
sentAudioStream = origAudioStream.clone();
// Smart Disconnect: Old connection dies immediately upon success origAudioTrack = event.track;
if (currentUpstreamPC && currentUpstreamPC !== newPC) { displayedAudioTrack = origAudioTrack.clone();
const oldPC = currentUpstreamPC; sentAudioTrack = origAudioTrack.clone();
setTimeout(() => { }
oldPC.close();
oldUpstreamPCs = oldUpstreamPCs.filter(pc => pc !== oldPC);
}, 1000);
}
currentUpstreamPC = newPC;
};
newPC.onicecandidate = (event) => { // Rebuild displayedStream
if (event.candidate) socket.emit('signal_msg', { target: senderId, type: 'candidate', candidate: event.candidate }); const displayedStream = new MediaStream();
}; if (displayedVideoTrack) displayedStream.addTrack(displayedVideoTrack);
if (displayedAudioTrack) displayedStream.addTrack(displayedAudioTrack);
await newPC.setRemoteDescription(new RTCSessionDescription(sdp)); remoteVideo.srcObject = displayedStream;
const answer = await newPC.createAnswer(); statusDiv.innerText = `Status: Connected | ID: ${socket.id}`;
await newPC.setLocalDescription(answer);
socket.emit('signal_msg', { target: senderId, type: 'answer', sdp: answer }); if (currentDownstreamPC) {
console.log('Relaying new upstream stream to downstream');
const videoSender = currentDownstreamPC.getSenders().find((s) => s.track && s.track.kind === 'video');
const audioSender = currentDownstreamPC.getSenders().find((s) => s.track && s.track.kind === 'video');
if (videoSender) await videoSender.replaceTrack(sentVideoTrack);
if (audioSender) await audioSender.replaceTrack(sentAudioTrack);
}
// Smart Disconnect: Old connection dies immediately upon success
if (currentUpstreamPC && currentUpstreamPC !== newPC) {
const oldPC = currentUpstreamPC;
setTimeout(() => {
oldPC.close();
oldUpstreamPCs = oldUpstreamPCs.filter((pc) => pc !== oldPC);
}, 1000);
}
currentUpstreamPC = newPC;
};
newPC.onicecandidate = (event) => {
if (event.candidate) socket.emit('signal_msg', { target: senderId, type: 'candidate', candidate: event.candidate });
};
await newPC.setRemoteDescription(new RTCSessionDescription(sdp));
const answer = await newPC.createAnswer();
await newPC.setLocalDescription(answer);
socket.emit('signal_msg', { target: senderId, type: 'answer', sdp: answer });
} }
async function setupDownstreamConnection(targetId) { async function setupDownstreamConnection(targetId) {
if (currentDownstreamPC) { if (currentDownstreamPC) {
const oldPC = currentDownstreamPC; const oldPC = currentDownstreamPC;
oldDownstreamPCs.push(oldPC); oldDownstreamPCs.push(oldPC);
setTimeout(() => { setTimeout(() => {
oldPC.close(); oldPC.close();
oldDownstreamPCs = oldDownstreamPCs.filter(pc => pc !== oldPC); oldDownstreamPCs = oldDownstreamPCs.filter((pc) => pc !== oldPC);
}, 5000); }, 5000);
} }
currentDownstreamPC = new RTCPeerConnection({ iceServers }); currentDownstreamPC = new RTCPeerConnection({ iceServers });
if (localStream) { if (localStream) {
localStream.getTracks().forEach(track => currentDownstreamPC.addTrack(track, localStream)); console.log('Sending local stream tracks to downstream');
} else if (currentUpstreamPC) { localStream.getTracks().forEach((track) => currentDownstreamPC.addTrack(track, localStream));
currentUpstreamPC.getReceivers().forEach(receiver => { } else if (currentUpstreamPC) {
if (receiver.track) currentDownstreamPC.addTrack(receiver.track, remoteVideo.srcObject); console.log('Relaying upstream stream tracks to downstream');
}); // currentDownstreamPC.addTrack(sentVideoTrack, sentVideoStream);
}
currentDownstreamPC.onicecandidate = (event) => { currentUpstreamPC.getReceivers().map((receiver) => {
if (event.candidate) socket.emit('signal_msg', { target: targetId, type: 'candidate', candidate: event.candidate }); console.log('Receiver track:', receiver.track);
}; if (!receiver.track) return;
const offer = await currentDownstreamPC.createOffer(); const sentTrack = receiver.track.kind === 'video' ? sentVideoTrack : sentAudioTrack;
offer.sdp = offer.sdp.replace(/b=AS:([0-9]+)/g, 'b=AS:4000'); const sentStream = receiver.track.kind === 'video' ? sentVideoStream : sentAudioStream;
if (!offer.sdp.includes('b=AS:')) offer.sdp = offer.sdp.replace(/(m=video.*\r\n)/, '$1b=AS:4000\r\n'); currentDownstreamPC.addTrack(sentTrack, sentStream);
});
}
await currentDownstreamPC.setLocalDescription(offer); currentDownstreamPC.onicecandidate = (event) => {
socket.emit('signal_msg', { target: targetId, type: 'offer', sdp: offer }); if (event.candidate) socket.emit('signal_msg', { target: targetId, type: 'candidate', candidate: event.candidate });
} };
await Promise.all(
currentDownstreamPC.getSenders().map(async (sender) => {
const params = sender.getParameters();
params.encodings = params.encodings.map((enc) => {
enc.maxBitrate = 200_000_000;
enc.maxFramerate = 60;
enc.scaleResolutionDownBy = 1.0;
enc.priority = 'high';
return enc;
});
params.degradationPreference = 'maintain-resolution';
await sender.setParameters(params);
})
);
const offer = await currentDownstreamPC.createOffer();
// offer.sdp = offer.sdp.replace(/b=AS:([0-9]+)/g, 'b=AS:4000');
// if (!offer.sdp.includes('b=AS:')) offer.sdp = offer.sdp.replace(/(m=video.*\r\n)/, '$1b=AS:4000\r\n');
await currentDownstreamPC.setLocalDescription(offer);
socket.emit('signal_msg', { target: targetId, type: 'offer', sdp: offer });
}
// --- 6. Debug Metrics (bitrate / loss / fps) ---
async function pollPeerMetrics() {
try {
const upstreamResult = currentUpstreamPC
? await collectInboundMetrics(currentUpstreamPC, metricsHistory.upstream)
: null;
const downstreamResult = currentDownstreamPC
? await collectOutboundMetrics(currentDownstreamPC, metricsHistory.downstream)
: null;
metricsHistory.upstream = upstreamResult
? upstreamResult.snapshot
: currentUpstreamPC
? metricsHistory.upstream
: null;
metricsHistory.downstream = downstreamResult
? downstreamResult.snapshot
: currentDownstreamPC
? metricsHistory.downstream
: null;
renderMetrics(upstreamResult ? upstreamResult.display : null, downstreamResult ? downstreamResult.display : null);
// Stream metrics to the monitor dashboard
socket.emit('report_metrics', {
inbound: upstreamResult ? upstreamResult.display : null,
outbound: downstreamResult ? downstreamResult.display : null,
});
} catch (err) {
console.warn('Metrics poll failed', err);
}
}
async function collectInboundMetrics(pc, previous) {
const stats = await pc.getStats();
let inboundVideo = null;
let candidatePair = null;
const tag = pc.__metricsTag || (pc.__metricsTag = Math.random().toString(36).slice(2));
const prev = previous && previous.tag === tag ? previous : null;
stats.forEach((report) => {
if (report.type === 'inbound-rtp' && report.kind === 'video' && !report.isRemote) inboundVideo = report;
if (report.type === 'candidate-pair' && report.state === 'succeeded' && report.nominated) candidatePair = report;
});
if (!inboundVideo) return null;
const deltaMs = prev ? inboundVideo.timestamp - prev.timestamp : null;
const bytesDelta = prev ? inboundVideo.bytesReceived - prev.bytesReceived : null;
const bitrateKbps = deltaMs && deltaMs > 0 && bytesDelta >= 0 ? (bytesDelta * 8) / deltaMs : null; // timestamp is ms
const framesDelta =
prev && inboundVideo.framesDecoded !== undefined && prev.framesDecoded !== undefined
? inboundVideo.framesDecoded - prev.framesDecoded
: null;
const fps = framesDelta !== null && deltaMs && deltaMs > 0 ? (framesDelta * 1000) / deltaMs : null;
const packetLossPct =
inboundVideo.packetsLost !== undefined && inboundVideo.packetsReceived !== undefined
? (inboundVideo.packetsLost / (inboundVideo.packetsReceived + inboundVideo.packetsLost)) * 100
: null;
const jitterMs = inboundVideo.jitter !== undefined ? inboundVideo.jitter * 1000 : null;
const rttMs =
candidatePair && candidatePair.currentRoundTripTime !== undefined
? candidatePair.currentRoundTripTime * 1000
: null;
const codecReport = inboundVideo.codecId && stats.get ? stats.get(inboundVideo.codecId) : null;
const codecLabel = codecReport ? codecReport.mimeType || codecReport.codecId || codecReport.sdpFmtpLine || '' : null;
return {
display: {
bitrateKbps,
fps,
resolution:
inboundVideo.frameWidth && inboundVideo.frameHeight
? `${inboundVideo.frameWidth}x${inboundVideo.frameHeight}`
: null,
packetLossPct,
jitterMs,
rttMs,
pli: inboundVideo.pliCount,
nack: inboundVideo.nackCount,
fir: inboundVideo.firCount,
framesDropped: inboundVideo.framesDropped,
codec: codecLabel,
state: pc.iceConnectionState || pc.connectionState,
},
snapshot: {
timestamp: inboundVideo.timestamp,
bytesReceived: inboundVideo.bytesReceived || 0,
framesDecoded: inboundVideo.framesDecoded || 0,
tag,
},
};
}
async function collectOutboundMetrics(pc, previous) {
const stats = await pc.getStats();
let outboundVideo = null;
let remoteInbound = null;
let candidatePair = null;
const tag = pc.__metricsTag || (pc.__metricsTag = Math.random().toString(36).slice(2));
const prev = previous && previous.tag === tag ? previous : null;
stats.forEach((report) => {
if (report.type === 'outbound-rtp' && report.kind === 'video' && !report.isRemote) outboundVideo = report;
if (report.type === 'remote-inbound-rtp' && report.kind === 'video') remoteInbound = report;
if (report.type === 'candidate-pair' && report.state === 'succeeded' && report.nominated) candidatePair = report;
});
if (!outboundVideo) return null;
const deltaMs = prev ? outboundVideo.timestamp - prev.timestamp : null;
const bytesDelta = prev ? outboundVideo.bytesSent - prev.bytesSent : null;
const bitrateKbps = deltaMs && deltaMs > 0 && bytesDelta >= 0 ? (bytesDelta * 8) / deltaMs : null;
const framesDelta =
prev && outboundVideo.framesEncoded !== undefined && prev.framesEncoded !== undefined
? outboundVideo.framesEncoded - prev.framesEncoded
: null;
const fps = framesDelta !== null && deltaMs && deltaMs > 0 ? (framesDelta * 1000) / deltaMs : null;
let packetLossPct = null;
if (remoteInbound && remoteInbound.packetsLost !== undefined && remoteInbound.packetsReceived !== undefined) {
packetLossPct = (remoteInbound.packetsLost / (remoteInbound.packetsReceived + remoteInbound.packetsLost)) * 100;
}
const rttMs =
candidatePair && candidatePair.currentRoundTripTime !== undefined
? candidatePair.currentRoundTripTime * 1000
: null;
const codecReport = outboundVideo.codecId && stats.get ? stats.get(outboundVideo.codecId) : null;
const codecLabel = codecReport ? codecReport.mimeType || codecReport.codecId || codecReport.sdpFmtpLine || '' : null;
return {
display: {
bitrateKbps,
fps,
resolution:
outboundVideo.frameWidth && outboundVideo.frameHeight
? `${outboundVideo.frameWidth}x${outboundVideo.frameHeight}`
: null,
packetLossPct,
rttMs,
qualityLimit: outboundVideo.qualityLimitationReason || 'none',
nack: outboundVideo.nackCount,
pli: outboundVideo.pliCount,
fir: outboundVideo.firCount,
retransmits: outboundVideo.retransmittedPacketsSent,
codec: codecLabel,
state: pc.iceConnectionState || pc.connectionState,
},
snapshot: {
timestamp: outboundVideo.timestamp,
bytesSent: outboundVideo.bytesSent || 0,
framesEncoded: outboundVideo.framesEncoded || 0,
tag,
},
};
}
function renderMetrics(inboundDisplay, outboundDisplay) {
if (!currentUpstreamPC) {
upstreamMetricsBox.innerHTML = 'No upstream peer (head broadcaster).';
} else if (!inboundDisplay) {
upstreamMetricsBox.innerHTML = 'Collecting inbound stats...';
} else {
upstreamMetricsBox.innerHTML = metricsLines([
['State', inboundDisplay.state || '--'],
['Bitrate', formatBitrate(inboundDisplay.bitrateKbps)],
['FPS', formatNumber(inboundDisplay.fps)],
['Resolution', inboundDisplay.resolution || '--'],
['Loss', formatPercent(inboundDisplay.packetLossPct)],
['Jitter', formatMillis(inboundDisplay.jitterMs)],
['RTT', formatMillis(inboundDisplay.rttMs)],
['PLI/NACK/FIR', formatTriple(inboundDisplay.pli, inboundDisplay.nack, inboundDisplay.fir)],
['Frames Dropped', formatCount(inboundDisplay.framesDropped)],
['Codec', inboundDisplay.codec || '--'],
]);
}
if (!currentDownstreamPC) {
downstreamMetricsBox.innerHTML = 'No downstream peer connected.';
} else if (!outboundDisplay) {
downstreamMetricsBox.innerHTML = 'Collecting outbound stats...';
} else {
downstreamMetricsBox.innerHTML = metricsLines([
['State', outboundDisplay.state || '--'],
['Bitrate', formatBitrate(outboundDisplay.bitrateKbps)],
['FPS', formatNumber(outboundDisplay.fps)],
['Resolution', outboundDisplay.resolution || '--'],
['Loss (remote)', formatPercent(outboundDisplay.packetLossPct)],
['RTT', formatMillis(outboundDisplay.rttMs)],
['Quality Limit', outboundDisplay.qualityLimit || '--'],
['PLI/NACK/FIR', formatTriple(outboundDisplay.pli, outboundDisplay.nack, outboundDisplay.fir)],
['Retransmits', formatCount(outboundDisplay.retransmits)],
['Codec', outboundDisplay.codec || '--'],
]);
}
}
function metricsLines(rows) {
return rows
.map(([label, value]) => `<div class="metrics-line"><span>${label}</span><span>${value}</span></div>`)
.join('');
}
function formatNumber(value, decimals = 1) {
return Number.isFinite(value) ? value.toFixed(decimals) : '--';
}
function formatBitrate(kbps) {
return Number.isFinite(kbps) ? `${kbps.toFixed(0)} kbps` : '--';
}
function formatPercent(value) {
return Number.isFinite(value) ? `${value.toFixed(1)}%` : '--';
}
function formatMillis(value) {
return Number.isFinite(value) ? `${value.toFixed(1)} ms` : '--';
}
function formatCount(value) {
return Number.isFinite(value) ? `${value}` : '--';
}
function formatTriple(a, b, c) {
const pa = Number.isFinite(a) ? a : '-';
const pb = Number.isFinite(b) ? b : '-';
const pc = Number.isFinite(c) ? c : '-';
return `${pa}/${pb}/${pc}`;
}

View File

@ -1,266 +1,318 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Strandcast</title>
<style>
/* --- RESET & BASICS --- */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<head> body {
<meta charset="UTF-8"> font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> background: #0a0a0a;
<title>Strandcast</title> color: #eee;
<style> text-align: center;
/* --- RESET & BASICS --- */ min-height: 100vh;
* { display: flex;
box-sizing: border-box; flex-direction: column;
margin: 0; }
padding: 0;
}
body { /* --- NAVIGATION BAR --- */
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; .navbar {
background: #0a0a0a; background-color: #111;
color: #eee; border-bottom: 1px solid #333;
text-align: center; padding: 15px 20px;
min-height: 100vh; display: flex;
display: flex; justify-content: space-between;
flex-direction: column; align-items: center;
} }
/* --- NAVIGATION BAR --- */ .navbar .brand {
.navbar { color: #00d2ff;
background-color: #111; font-size: 18px;
border-bottom: 1px solid #333; font-weight: bold;
padding: 15px 20px; text-decoration: none;
display: flex; }
justify-content: space-between;
align-items: center;
}
.navbar .brand { .nav-links a {
color: #00d2ff; color: #888;
font-size: 18px; text-decoration: none;
font-weight: bold; margin-left: 20px;
text-decoration: none; font-size: 14px;
} padding: 5px;
}
.nav-links a { .nav-links a:hover {
color: #888; color: #fff;
text-decoration: none; }
margin-left: 20px;
font-size: 14px;
padding: 5px;
}
.nav-links a:hover { .nav-links a.active {
color: #fff; color: #fff;
} font-weight: bold;
border-bottom: 2px solid #00d2ff;
}
.nav-links a.active { /* --- LAYOUT CONTAINERS --- */
color: #fff; .container {
font-weight: bold; flex: 1;
border-bottom: 2px solid #00d2ff; display: flex;
} flex-direction: column;
align-items: center;
padding: 20px;
width: 100%;
}
/* --- LAYOUT CONTAINERS --- */ h1 {
.container { margin-bottom: 20px;
flex: 1; font-weight: 300;
display: flex; font-size: 24px;
flex-direction: column; }
align-items: center;
padding: 20px;
width: 100%;
}
h1 { /* --- LOBBY STYLES --- */
margin-bottom: 20px; #lobby-view {
font-weight: 300; width: 100%;
font-size: 24px; max-width: 500px;
} }
/* --- LOBBY STYLES --- */ .card {
#lobby-view { background: #161616;
width: 100%; border: 1px solid #333;
max-width: 500px; border-radius: 12px;
} padding: 20px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
margin-bottom: 20px;
}
.card { /* Stream List */
background: #161616; ul {
border: 1px solid #333; list-style: none;
border-radius: 12px; padding: 0;
padding: 20px; }
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
margin-bottom: 20px;
}
/* Stream List */ li {
ul { background: #222;
list-style: none; margin: 8px 0;
padding: 0; padding: 15px;
} border-radius: 8px;
/* Softer corners for mobile */
cursor: pointer;
border: 1px solid #333;
text-align: left;
display: flex;
justify-content: space-between;
align-items: center;
/* Make tap target easier */
min-height: 50px;
}
li { li:active {
background: #222; background: #333;
margin: 8px 0; transform: scale(0.98);
padding: 15px; }
border-radius: 8px;
/* Softer corners for mobile */
cursor: pointer;
border: 1px solid #333;
text-align: left;
display: flex;
justify-content: space-between;
align-items: center;
/* Make tap target easier */
min-height: 50px;
}
li:active { /* Inputs - 16px font prevents iOS zoom */
background: #333; input[type='text'] {
transform: scale(0.98); width: 100%;
} padding: 12px;
background: #000;
border: 1px solid #444;
color: white;
border-radius: 6px;
margin-bottom: 15px;
outline: none;
font-size: 16px;
}
/* Inputs - 16px font prevents iOS zoom */ input[type='file'] {
input[type="text"] { width: 100%;
width: 100%; padding: 10px;
padding: 12px; background: #222;
background: #000; color: #ccc;
border: 1px solid #444; border-radius: 6px;
color: white; margin-bottom: 15px;
border-radius: 6px; border: 1px solid #333;
margin-bottom: 15px; font-size: 14px;
outline: none; }
font-size: 16px;
}
input[type="file"] { button {
width: 100%; width: 100%;
padding: 10px; padding: 14px;
background: #222; /* Larger tap area */
color: #ccc; cursor: pointer;
border-radius: 6px; background: linear-gradient(135deg, #007bff, #0056b3);
margin-bottom: 15px; color: white;
border: 1px solid #333; border: none;
font-size: 14px; border-radius: 8px;
} font-weight: bold;
font-size: 16px;
/* Prevent sticky hover on mobile */
-webkit-tap-highlight-color: transparent;
}
button { button:active {
width: 100%; opacity: 0.8;
padding: 14px; transform: scale(0.98);
/* Larger tap area */ }
cursor: pointer;
background: linear-gradient(135deg, #007bff, #0056b3);
color: white;
border: none;
border-radius: 8px;
font-weight: bold;
font-size: 16px;
/* Prevent sticky hover on mobile */
-webkit-tap-highlight-color: transparent;
}
button:active { button.leave-btn {
opacity: 0.8; background: #d32f2f;
transform: scale(0.98); margin-top: 20px;
} width: 100%;
}
button.leave-btn { /* --- STREAM VIEW --- */
background: #d32f2f; #stream-view {
margin-top: 20px; display: none;
width: 100%; width: 100%;
} }
/* --- STREAM VIEW --- */ video {
#stream-view { width: 100%;
display: none; /* Maintain aspect ratio */
width: 100%; aspect-ratio: 16 / 9;
} background: #000;
border-radius: 8px;
margin: 10px 0;
}
video { #status {
width: 100%; color: #00d2ff;
/* Maintain aspect ratio */ margin-top: 10px;
aspect-ratio: 16 / 9; font-family: monospace;
background: #000; background: #111;
border-radius: 8px; display: inline-block;
margin: 10px 0; padding: 8px 20px;
object-fit: cover; border-radius: 20px;
} border: 1px solid #333;
font-size: 14px;
}
#status { /* --- DEBUG METRICS --- */
color: #00d2ff; #debug-metrics {
margin-top: 10px; margin-top: 14px;
font-family: monospace; width: 100%;
background: #111; display: grid;
display: inline-block; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
padding: 8px 20px; gap: 12px;
border-radius: 20px; }
border: 1px solid #333;
font-size: 14px;
}
/* --- MOBILE MEDIA QUERY --- */ .metrics-card {
@media (max-width: 600px) { background: #111;
.navbar { border: 1px solid #222;
flex-direction: column; border-radius: 10px;
padding: 10px; padding: 12px 14px;
} text-align: left;
font-family: monospace;
}
.navbar .brand { .metrics-title {
margin-bottom: 10px; color: #00d2ff;
} font-size: 12px;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
}
.nav-links a { .metrics-line {
margin: 0 10px; display: flex;
} justify-content: space-between;
color: #ccc;
font-size: 12px;
margin: 4px 0;
}
.container { .metrics-note {
padding: 10px; color: #777;
} font-size: 12px;
}
.card { /* --- MOBILE MEDIA QUERY --- */
padding: 15px; @media (max-width: 600px) {
} .navbar {
flex-direction: column;
padding: 10px;
}
h1 { .navbar .brand {
font-size: 20px; margin-bottom: 10px;
} }
}
</style>
</head>
<body> .nav-links a {
<nav class="navbar"> margin: 0 10px;
<a href="/" class="brand">Strandcast</a> }
<div class="nav-links">
<a href="/" class="active">Streams</a>
<a href="/monitor.html">Monitor</a>
</div>
</nav>
<div class="container">
<div id="lobby-view">
<h1>Join a Broadcast</h1>
<div class="card">
<h3 style="margin-bottom:15px; color:#aaa; font-size:12px; text-transform:uppercase; letter-spacing:1px;">Active Streams</h3>
<ul id="streamList">
<li style="color:#777; cursor:default; background:transparent; border:none; justify-content:center;">Searching...</li>
</ul>
</div>
<div class="card">
<h3 style="margin-bottom:15px; color:#aaa; font-size:12px; text-transform:uppercase; letter-spacing:1px;">Go Live</h3>
<input type="text" id="streamNameInput" placeholder="Stream Name">
<div style="text-align: left; margin-bottom: 8px;">
<label style="color: #666; font-size: 11px; font-weight:bold;">SOURCE (OPTIONAL):</label>
</div>
<input type="file" id="videoFileInput" accept="video/*">
<button onclick="startStream()">Start Broadcasting</button>
</div>
</div>
<div id="stream-view">
<h2 id="currentStreamTitle" style="color:#fff; margin-bottom:10px; font-size: 18px;">Stream Name</h2>
<video id="localVideo" autoplay muted playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>
<div id="status">Status: Connecting...</div>
<button onclick="leaveStream()" class="leave-btn">Leave Stream</button>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html> .container {
padding: 10px;
}
.card {
padding: 15px;
}
h1 {
font-size: 20px;
}
}
</style>
</head>
<body>
<nav class="navbar">
<a href="/" class="brand">Strandcast</a>
<div class="nav-links">
<a href="/" class="active">Streams</a>
<a href="/monitor.html">Monitor</a>
</div>
</nav>
<div class="container">
<div id="lobby-view">
<h1>Join a Broadcast</h1>
<div class="card">
<h3 style="margin-bottom: 15px; color: #aaa; font-size: 12px; text-transform: uppercase; letter-spacing: 1px">
Active Streams
</h3>
<ul id="streamList">
<li style="color: #777; cursor: default; background: transparent; border: none; justify-content: center">
Searching...
</li>
</ul>
</div>
<div class="card">
<h3 style="margin-bottom: 15px; color: #aaa; font-size: 12px; text-transform: uppercase; letter-spacing: 1px">
Go Live
</h3>
<input type="text" id="streamNameInput" placeholder="Stream Name" />
<div style="text-align: left; margin-bottom: 8px">
<label style="color: #666; font-size: 11px; font-weight: bold">SOURCE (OPTIONAL):</label>
</div>
<input type="file" id="videoFileInput" accept="video/*" />
<button onclick="startStream()">Start Broadcasting</button>
</div>
</div>
<div id="stream-view">
<h2 id="currentStreamTitle" style="color: #fff; margin-bottom: 10px; font-size: 18px">Stream Name</h2>
<video id="localVideo" autoplay muted playsinline></video>
<video id="remoteVideo" autoplay playsinline></video>
<div id="status">Status: Connecting...</div>
<div id="debug-metrics">
<div class="metrics-card">
<div class="metrics-title">Inbound (from upstream)</div>
<div id="upstreamMetrics" class="metrics-body metrics-note">Waiting for data...</div>
</div>
<div class="metrics-card">
<div class="metrics-title">Outbound (to downstream)</div>
<div id="downstreamMetrics" class="metrics-body metrics-note">Waiting for data...</div>
</div>
</div>
<button onclick="leaveStream()" class="leave-btn">Leave Stream</button>
</div>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>

View File

@ -1,214 +1,285 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Strandcast Monitor</title>
<style>
/* --- RESET & BASICS --- */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
<head> body {
<meta charset="UTF-8"> /* Unified Font Stack */
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
<title>Strandcast Monitor</title> background: #0a0a0a;
<style> color: #eee;
/* --- RESET & BASICS --- */ min-height: 100vh;
* { display: flex;
box-sizing: border-box; flex-direction: column;
margin: 0; }
padding: 0;
}
body { /* --- NAVIGATION BAR --- */
/* Unified Font Stack */ .navbar {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #111;
background: #0a0a0a; border-bottom: 1px solid #333;
color: #eee; padding: 15px 20px;
min-height: 100vh; display: flex;
display: flex; justify-content: space-between;
flex-direction: column; align-items: center;
} }
/* --- NAVIGATION BAR --- */ .navbar .brand {
.navbar { color: #00d2ff;
background-color: #111; font-size: 18px;
border-bottom: 1px solid #333; font-weight: bold;
padding: 15px 20px; text-decoration: none;
display: flex; }
justify-content: space-between;
align-items: center;
}
.navbar .brand { .nav-links a {
color: #00d2ff; color: #888;
font-size: 18px; text-decoration: none;
font-weight: bold; margin-left: 20px;
text-decoration: none; font-size: 14px;
} padding: 5px;
}
.nav-links a { .nav-links a:hover {
color: #888; color: #fff;
text-decoration: none; }
margin-left: 20px;
font-size: 14px;
padding: 5px;
}
.nav-links a:hover { .nav-links a.active {
color: #fff; color: #fff;
} font-weight: bold;
border-bottom: 2px solid #00d2ff;
}
.nav-links a.active { /* --- DASHBOARD --- */
color: #fff; h1 {
font-weight: bold; text-align: center;
border-bottom: 2px solid #00d2ff; margin: 20px 0;
} font-weight: 300;
font-size: 24px;
/* Matched to index.html */
}
/* --- DASHBOARD --- */ #dashboard {
h1 { padding: 10px 20px;
text-align: center; flex: 1;
margin: 20px 0; overflow-x: hidden;
font-weight: 300; width: 100%;
font-size: 24px; max-width: 1200px;
/* Matched to index.html */ margin: 0 auto;
} }
#dashboard { .stream-container {
padding: 10px 20px; /* Matched to .card in index.html */
flex: 1; background: #161616;
overflow-x: hidden; border: 1px solid #333;
width: 100%; border-radius: 12px;
max-width: 1200px; padding: 20px;
margin: 0 auto; margin-bottom: 20px;
} box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
}
.stream-container { .stream-title {
/* Matched to .card in index.html */ color: #00d2ff;
background: #161616; font-size: 14px;
border: 1px solid #333; margin-bottom: 15px;
border-radius: 12px; font-weight: bold;
padding: 20px; text-transform: uppercase;
margin-bottom: 20px; letter-spacing: 1px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5); border-bottom: 1px solid #333;
} padding-bottom: 8px;
}
.stream-title { /* The scrolling wrapper */
color: #00d2ff; .chain-wrapper {
font-size: 14px; overflow-x: auto;
margin-bottom: 15px; -webkit-overflow-scrolling: touch;
font-weight: bold; padding-bottom: 10px;
text-transform: uppercase; }
letter-spacing: 1px;
border-bottom: 1px solid #333;
padding-bottom: 8px;
}
/* The scrolling wrapper */ .chain-visual {
.chain-wrapper { display: flex;
overflow-x: auto; align-items: stretch;
-webkit-overflow-scrolling: touch; gap: 14px;
padding-bottom: 10px; flex-wrap: wrap;
} width: 100%;
}
.chain-visual { /* Node wrapper: arrow + card */
display: flex; .node-wrapper {
align-items: center; display: flex;
width: max-content; align-items: stretch;
} gap: 10px;
padding: 0;
min-width: 210px;
max-width: 240px;
background: transparent;
border: none;
box-shadow: none;
}
/* The Nodes */ .node-row {
.node { display: flex;
display: flex; align-items: center;
flex-direction: column; gap: 10px;
align-items: center; height: 100%;
justify-content: center; }
width: 90px;
height: 70px;
border-radius: 8px;
/* Softer corners */
background: #222;
border: 1px solid #444;
position: relative;
margin: 0 4px;
transition: all 0.2s;
}
.node-id { .node-card {
font-size: 11px; display: grid;
font-weight: bold; grid-template-rows: auto 1fr;
margin-bottom: 4px; gap: 8px;
color: #fff; background: #0f0f0f;
} border: 1px solid #222;
border-radius: 10px;
padding: 10px;
flex: 1;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.35);
justify-items: center;
}
.node-score { /* The Nodes */
font-size: 16px; .node {
font-weight: bold; display: flex;
} flex-direction: column;
align-items: center;
justify-content: center;
width: 86px;
height: 64px;
border-radius: 8px;
background: #222;
border: 1px solid #444;
position: relative;
transition: all 0.2s;
}
.node-role { .node-id {
font-size: 9px; font-size: 11px;
color: #888; font-weight: bold;
text-transform: uppercase; margin-bottom: 4px;
margin-top: 4px; color: #fff;
letter-spacing: 0.5px; }
}
/* Health Colors */ .node-score {
.healthy { font-size: 16px;
border-color: #00ff88; font-weight: bold;
color: #00ff88; }
box-shadow: 0 0 10px rgba(0, 255, 136, 0.05);
}
.meh { .node-role {
border-color: #ffaa00; font-size: 9px;
color: #ffaa00; color: #888;
} text-transform: uppercase;
margin-top: 4px;
letter-spacing: 0.5px;
}
.weak { .node-metrics {
border-color: #ff3333; font-size: 11px;
color: #ff3333; color: #ccc;
} line-height: 1.4;
background: #111;
border: 1px solid #222;
border-radius: 8px;
padding: 6px 8px;
}
/* Arrows */ .metrics-grid {
.arrow { display: grid;
font-size: 16px; grid-template-columns: 1fr;
color: #555; gap: 12px;
margin: 0 8px; }
}
/* --- MOBILE MEDIA QUERY --- */ .metric-row {
@media (max-width: 600px) { display: flex;
.navbar { justify-content: space-between;
flex-direction: column; gap: 12px;
padding: 10px; }
}
.navbar .brand { .metric-label {
margin-bottom: 10px; color: #888;
} font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.nav-links a { .metric-value {
margin: 0 10px; color: #e5e5e5;
} font-size: 12px;
text-align: right;
font-variant-numeric: tabular-nums;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 2px;
}
#dashboard { /* Health Colors */
padding: 10px; .healthy {
} border-color: #00ff88;
color: #00ff88;
box-shadow: 0 0 10px rgba(0, 255, 136, 0.05);
}
h1 { .meh {
font-size: 20px; border-color: #ffaa00;
} color: #ffaa00;
} }
</style>
</head>
<body> .weak {
<nav class="navbar"> border-color: #ff3333;
<a href="/" class="brand">Strandcast</a> color: #ff3333;
<div class="nav-links"> }
<a href="/">Streams</a>
<a href="/monitor.html" class="active">Monitor</a>
</div>
</nav>
<h1>Network Status</h1>
<div id="dashboard" style="text-align: center; color: #555;">Connecting...</div>
<script src="/socket.io/socket.io.js"></script>
<script src="monitor.js"></script>
</body>
</html> /* Arrows */
.arrow {
font-size: 16px;
color: #555;
align-self: center;
}
/* --- MOBILE MEDIA QUERY --- */
@media (max-width: 600px) {
.navbar {
flex-direction: column;
padding: 10px;
}
.navbar .brand {
margin-bottom: 10px;
}
.nav-links a {
margin: 0 10px;
}
#dashboard {
padding: 10px;
}
h1 {
font-size: 20px;
}
}
</style>
</head>
<body>
<nav class="navbar">
<a href="/" class="brand">Strandcast</a>
<div class="nav-links">
<a href="/">Streams</a>
<a href="/monitor.html" class="active">Monitor</a>
</div>
</nav>
<h1>Network Status</h1>
<div id="dashboard" style="text-align: center; color: #555">Connecting...</div>
<script src="/socket.io/socket.io.js"></script>
<script src="monitor.js"></script>
</body>
</html>

View File

@ -4,138 +4,179 @@ const dashboard = document.getElementById('dashboard');
// Identify as a monitor // Identify as a monitor
socket.emit('join_monitor'); socket.emit('join_monitor');
socket.on('monitor_update', ({ streams, scores }) => { socket.on('monitor_update', ({ streams, scores, metrics }) => {
updateDashboard(streams, scores); updateDashboard(streams, scores, metrics || {});
}); });
function updateDashboard(streams, scores) { function updateDashboard(streams, scores, metrics) {
const activeStreamNames = Object.keys(streams); const activeStreamNames = Object.keys(streams);
// 1. Remove streams that no longer exist // 1. Remove streams that no longer exist
const existingContainers = document.querySelectorAll('.stream-container'); const existingContainers = document.querySelectorAll('.stream-container');
existingContainers.forEach(container => { existingContainers.forEach((container) => {
const name = container.getAttribute('data-stream'); const name = container.getAttribute('data-stream');
if (!streams[name]) { if (!streams[name]) {
container.remove(); container.remove();
} }
}); });
// 2. Add or Update streams // 2. Add or Update streams
if (activeStreamNames.length === 0) { if (activeStreamNames.length === 0) {
// If empty, show message (only if not already showing it) // If empty, show message (only if not already showing it)
if (!dashboard.innerText.includes("No Active Streams")) { if (!dashboard.innerText.includes('No Active Streams')) {
dashboard.innerHTML = "<div style='text-align:center; color:#555; margin-top:50px;'>No Active Streams</div>"; dashboard.innerHTML = "<div style='text-align:center; color:#555; margin-top:50px;'>No Active Streams</div>";
} }
return; return;
} else { } else {
// FIX: Check if we are still showing a text message (Connecting, No Active Streams, etc) // FIX: Check if we are still showing a text message (Connecting, No Active Streams, etc)
// If we have streams but no stream containers yet, clear the text. // If we have streams but no stream containers yet, clear the text.
if (!dashboard.querySelector('.stream-container')) { if (!dashboard.querySelector('.stream-container')) {
dashboard.innerHTML = ""; dashboard.innerHTML = '';
} }
} }
activeStreamNames.forEach(name => { activeStreamNames.forEach((name) => {
let container = document.getElementById(`stream-${name}`); let container = document.getElementById(`stream-${name}`);
const chain = streams[name]; const chain = streams[name];
// Create Container if it doesn't exist // Create Container if it doesn't exist
if (!container) { if (!container) {
container = document.createElement('div'); container = document.createElement('div');
container.id = `stream-${name}`; container.id = `stream-${name}`;
container.className = 'stream-container'; container.className = 'stream-container';
container.setAttribute('data-stream', name); container.setAttribute('data-stream', name);
// Structure // Structure
const title = document.createElement('div'); const title = document.createElement('div');
title.className = 'stream-title'; title.className = 'stream-title';
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.className = 'chain-wrapper'; wrapper.className = 'chain-wrapper';
const visual = document.createElement('div'); const visual = document.createElement('div');
visual.className = 'chain-visual'; visual.className = 'chain-visual';
wrapper.appendChild(visual); wrapper.appendChild(visual);
container.appendChild(title); container.appendChild(title);
container.appendChild(wrapper); container.appendChild(wrapper);
dashboard.appendChild(container); dashboard.appendChild(container);
} }
// Update Title // Update Title
const titleEl = container.querySelector('.stream-title'); const titleEl = container.querySelector('.stream-title');
titleEl.innerText = `Stream: ${name} (${chain.length} nodes)`; titleEl.innerText = `Stream: ${name} (${chain.length} nodes)`;
// Update Nodes // Update Nodes
updateChainVisual(container.querySelector('.chain-visual'), chain, scores); updateChainVisual(container.querySelector('.chain-visual'), chain, scores, metrics);
}); });
} }
function updateChainVisual(visualContainer, chain, scores) { function updateChainVisual(visualContainer, chain, scores, metrics) {
const existingNodes = Array.from(visualContainer.querySelectorAll('.node-wrapper')); const existingNodes = Array.from(visualContainer.querySelectorAll('.node-wrapper'));
const nodeMap = {}; const nodeMap = {};
existingNodes.forEach(el => nodeMap[el.getAttribute('data-id')] = el); existingNodes.forEach((el) => (nodeMap[el.getAttribute('data-id')] = el));
const processedIds = new Set(); const processedIds = new Set();
chain.forEach((socketId, index) => { chain.forEach((socketId, index) => {
processedIds.add(socketId); processedIds.add(socketId);
const score = scores[socketId] !== undefined ? scores[socketId] : '??'; const score = scores[socketId] !== undefined ? scores[socketId] : '??';
let healthClass = 'meh'; let healthClass = 'meh';
if (score >= 80) healthClass = 'healthy'; if (score >= 80) healthClass = 'healthy';
if (score < 50) healthClass = 'weak'; if (score < 50) healthClass = 'weak';
if (index === 0) healthClass = 'healthy'; if (index === 0) healthClass = 'healthy';
const role = index === 0 ? "SOURCE" : (index === chain.length - 1 ? "VIEWER" : "RELAY"); const role = index === 0 ? 'SOURCE' : index === chain.length - 1 ? 'VIEWER' : 'RELAY';
const shortId = socketId.substring(0, 4); const shortId = socketId.substring(0, 4);
let nodeWrapper = nodeMap[socketId]; const metric = metrics[socketId] || {};
let nodeWrapper = nodeMap[socketId];
// --- CREATE --- // --- CREATE ---
if (!nodeWrapper) { if (!nodeWrapper) {
nodeWrapper = document.createElement('div'); nodeWrapper = document.createElement('div');
nodeWrapper.className = 'node-wrapper'; nodeWrapper.className = 'node-wrapper';
nodeWrapper.setAttribute('data-id', socketId); nodeWrapper.setAttribute('data-id', socketId);
nodeWrapper.style.display = 'flex';
nodeWrapper.style.alignItems = 'center';
nodeWrapper.innerHTML = ` nodeWrapper.innerHTML = `
<div class="arrow"></div> <div class="node-row">
<div class="node"> <div class="arrow"></div>
<div class="node-role"></div> <div class="node-card">
<div class="node-id"></div> <div class="node">
<div class="node-score"></div> <div class="node-role"></div>
</div> <div class="node-id"></div>
`; <div class="node-score"></div>
</div>
<div class="node-metrics"></div>
</div>
</div>
`;
visualContainer.appendChild(nodeWrapper); visualContainer.appendChild(nodeWrapper);
} }
// --- UPDATE --- // --- UPDATE ---
// 1. Order (Preserve Scroll) // 1. Order (Preserve Scroll)
if (visualContainer.children[index] !== nodeWrapper) { if (visualContainer.children[index] !== nodeWrapper) {
visualContainer.insertBefore(nodeWrapper, visualContainer.children[index]); visualContainer.insertBefore(nodeWrapper, visualContainer.children[index]);
} }
// 2. Arrow Visibility // 2. Arrow Visibility
const arrow = nodeWrapper.querySelector('.arrow'); const arrow = nodeWrapper.querySelector('.arrow');
arrow.style.opacity = index === 0 ? "0" : "1"; arrow.style.opacity = index === 0 ? '0' : '1';
// 3. Data // 3. Data
const nodeEl = nodeWrapper.querySelector('.node'); const nodeEl = nodeWrapper.querySelector('.node');
nodeEl.className = `node ${healthClass}`; nodeEl.className = `node ${healthClass}`;
nodeWrapper.querySelector('.node-role').innerText = role; nodeWrapper.querySelector('.node-role').innerText = role;
nodeWrapper.querySelector('.node-id').innerText = shortId; nodeWrapper.querySelector('.node-id').innerText = shortId;
nodeWrapper.querySelector('.node-score').innerText = score; nodeWrapper.querySelector('.node-score').innerText = score;
});
// --- REMOVE --- const metricsBox = nodeWrapper.querySelector('.node-metrics');
existingNodes.forEach(el => { metricsBox.innerHTML = renderMetricsLines(metric.inbound, metric.outbound);
const id = el.getAttribute('data-id'); });
if (!processedIds.has(id)) {
el.remove(); // --- REMOVE ---
} existingNodes.forEach((el) => {
}); const id = el.getAttribute('data-id');
} if (!processedIds.has(id)) {
el.remove();
}
});
}
function renderMetricsLines(inbound, outbound) {
const rows = [];
rows.push(metricRow('Inbound', inbound ? formatMetricLines(inbound, true) : ['—']));
rows.push(metricRow('Outbound', outbound ? formatMetricLines(outbound, false) : ['—']));
return `<div class="metrics-grid">${rows.join('')}</div>`;
}
function metricRow(label, valueLines) {
const valueHtml = valueLines.map((v) => `<span>${v}</span>`).join('');
return `<div class="metric-row"><span class="metric-label">${label}</span><span class="metric-value">${valueHtml}</span></div>`;
}
function formatMetricLines(m, isInbound) {
const lines = [];
lines.push(fmtBitrate(m.bitrateKbps));
lines.push(`loss ${fmtPercent(m.packetLossPct)}`);
lines.push(`fps ${fmtNumber(m.fps)}`);
if (m.resolution) lines.push(m.resolution);
if (!isInbound && m.qualityLimit) lines.push(`limit ${m.qualityLimit}`);
return lines;
}
function fmtNumber(v) {
return Number.isFinite(v) ? v.toFixed(1) : '--';
}
function fmtBitrate(kbps) {
return Number.isFinite(kbps) ? `${kbps.toFixed(0)} kbps` : '--';
}
function fmtPercent(v) {
return Number.isFinite(v) ? `${v.toFixed(1)}%` : '--';
}

324
server.js
View File

@ -1,7 +1,7 @@
require('dotenv').config(); require('dotenv').config();
const express = require('express'); const express = require('express');
const http = require('http'); const http = require('http');
const { Server } = require("socket.io"); const { Server } = require('socket.io');
const axios = require('axios'); const axios = require('axios');
const app = express(); const app = express();
@ -12,17 +12,18 @@ app.use(express.static('public'));
// --- Cloudflare Credentials --- // --- Cloudflare Credentials ---
app.get('/api/get-turn-credentials', async (req, res) => { app.get('/api/get-turn-credentials', async (req, res) => {
try { try {
const response = await axios.post( // const response = await axios.post(
`https://rtc.live.cloudflare.com/v1/turn/keys/${process.env.CLOUDFLARE_APP_ID}/credentials/generate-ice-servers`, // `https://rtc.live.cloudflare.com/v1/turn/keys/${process.env.CLOUDFLARE_APP_ID}/credentials/generate-ice-servers`,
{ ttl: 86400 }, // { ttl: 86400 },
{ headers: { 'Authorization': `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json' } } // { headers: { 'Authorization': `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, 'Content-Type': 'application/json' } }
); // );
res.json(response.data); const response = await fetch(`https://strandcast.benglsoftware.com/api/get-turn-credentials`);
} catch (error) { res.json(await response.json());
console.error("Cloudflare Error:", error.message); } catch (error) {
res.json({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }); console.error('Cloudflare Error:', error.message);
} res.json({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
}
}); });
// --- STATE MANAGEMENT --- // --- STATE MANAGEMENT ---
@ -30,198 +31,205 @@ app.get('/api/get-turn-credentials', async (req, res) => {
const streams = {}; const streams = {};
const socketStreamMap = {}; // Helper: socketId -> StreamName (for fast lookups on disconnect) const socketStreamMap = {}; // Helper: socketId -> StreamName (for fast lookups on disconnect)
const scores = {}; // socketId -> Health Score (0-100) const scores = {}; // socketId -> Health Score (0-100)
const metrics = {}; // socketId -> { inbound, outbound, ts }
io.on('connection', (socket) => { io.on('connection', (socket) => {
console.log(`User connected: ${socket.id}`); console.log(`User connected: ${socket.id}`);
scores[socket.id] = 80; scores[socket.id] = 80;
// 0. Send the list of streams to the new user // 0. Send the list of streams to the new user
socket.emit('stream_list_update', Object.keys(streams)); socket.emit('stream_list_update', Object.keys(streams));
// A. Start New Stream // A. Start New Stream
socket.on('start_stream', (streamName) => { socket.on('start_stream', (streamName) => {
if (streams[streamName]) { if (streams[streamName]) {
socket.emit('error_msg', "Stream name already exists."); socket.emit('error_msg', 'Stream name already exists.');
return; return;
} }
if (socketStreamMap[socket.id]) { if (socketStreamMap[socket.id]) {
socket.emit('error_msg', "You are already in a stream."); socket.emit('error_msg', 'You are already in a stream.');
return; return;
} }
streams[streamName] = [socket.id]; streams[streamName] = [socket.id];
socketStreamMap[socket.id] = streamName; socketStreamMap[socket.id] = streamName;
console.log(`Stream started: ${streamName} by ${socket.id}`); console.log(`Stream started: ${streamName} by ${socket.id}`);
socket.emit('role_assigned', 'head'); socket.emit('role_assigned', 'head');
// Broadcast new list to everyone in the lobby // Broadcast new list to everyone in the lobby
io.emit('stream_list_update', Object.keys(streams)); io.emit('stream_list_update', Object.keys(streams));
}); });
// B. Join Existing Stream // B. Join Existing Stream
socket.on('join_stream', (streamName) => { socket.on('join_stream', (streamName) => {
const chain = streams[streamName]; const chain = streams[streamName];
if (!chain) { if (!chain) {
socket.emit('error_msg', "Stream does not exist."); socket.emit('error_msg', 'Stream does not exist.');
return; return;
} }
const upstreamPeerId = chain[chain.length - 1]; const upstreamPeerId = chain[chain.length - 1];
chain.push(socket.id); chain.push(socket.id);
socketStreamMap[socket.id] = streamName; socketStreamMap[socket.id] = streamName;
console.log(`User ${socket.id} joined stream "${streamName}". Upstream: ${upstreamPeerId}`); console.log(`User ${socket.id} joined stream "${streamName}". Upstream: ${upstreamPeerId}`);
// Tell Upstream to connect to ME // Tell Upstream to connect to ME
io.to(upstreamPeerId).emit('connect_to_downstream', { downstreamId: socket.id }); io.to(upstreamPeerId).emit('connect_to_downstream', { downstreamId: socket.id });
// Request Keyframe (Targeting the Head of THIS stream) // Request Keyframe (Targeting the Head of THIS stream)
setTimeout(() => { setTimeout(() => {
if (streams[streamName] && streams[streamName][0]) { if (streams[streamName] && streams[streamName][0]) {
io.to(streams[streamName][0]).emit('request_keyframe'); io.to(streams[streamName][0]).emit('request_keyframe');
} }
}, 2000); }, 2000);
}); });
// C. Signaling // C. Signaling
socket.on('signal_msg', ({ target, type, sdp, candidate }) => { socket.on('signal_msg', ({ target, type, sdp, candidate }) => {
io.to(target).emit('signal_msg', { sender: socket.id, type, sdp, candidate }); io.to(target).emit('signal_msg', { sender: socket.id, type, sdp, candidate });
}); });
// D. Score Updates // D. Score Updates
socket.on('update_score', (score) => { socket.on('update_score', (score) => {
scores[socket.id] = score; scores[socket.id] = score;
}); });
// E. Keyframe Relay // D2. Metrics Updates
socket.on('relay_keyframe_upstream', () => { socket.on('report_metrics', (payload) => {
const streamName = socketStreamMap[socket.id]; metrics[socket.id] = { ...payload, ts: Date.now() };
if (streamName && streams[streamName]) { });
io.to(streams[streamName][0]).emit('request_keyframe');
}
});
// F. Disconnects (Healing) // E. Keyframe Relay
socket.on('disconnect', () => { socket.on('relay_keyframe_upstream', () => {
delete scores[socket.id]; const streamName = socketStreamMap[socket.id];
const streamName = socketStreamMap[socket.id]; if (streamName && streams[streamName]) {
io.to(streams[streamName][0]).emit('request_keyframe');
}
});
if (!streamName) return; // User wasn't in a stream // F. Disconnects (Healing)
socket.on('disconnect', () => {
delete scores[socket.id];
delete metrics[socket.id];
const streamName = socketStreamMap[socket.id];
const chain = streams[streamName]; if (!streamName) return; // User wasn't in a stream
if (!chain) return;
const index = chain.indexOf(socket.id); const chain = streams[streamName];
if (index === -1) return; if (!chain) return;
console.log(`User ${socket.id} left stream "${streamName}". Index: ${index}`); const index = chain.indexOf(socket.id);
if (index === -1) return;
// Case 1: Head Left -> Destroy Stream console.log(`User ${socket.id} left stream "${streamName}". Index: ${index}`);
if (index === 0) {
delete streams[streamName];
// Notify everyone in this stream that it ended
chain.forEach(peerId => {
if (peerId !== socket.id) io.to(peerId).emit('stream_ended');
delete socketStreamMap[peerId];
});
io.emit('stream_list_update', Object.keys(streams)); // Update Lobby
return;
}
// Case 2: Tail Left -> Just pop // Case 1: Head Left -> Destroy Stream
if (index === chain.length - 1) { if (index === 0) {
chain.pop(); delete streams[streamName];
const newTail = chain[chain.length - 1]; // Notify everyone in this stream that it ended
if (newTail) io.to(newTail).emit('disconnect_downstream'); chain.forEach((peerId) => {
} if (peerId !== socket.id) io.to(peerId).emit('stream_ended');
// Case 3: Middle Left -> Stitch delete socketStreamMap[peerId];
else { });
const upstreamNode = chain[index - 1]; io.emit('stream_list_update', Object.keys(streams)); // Update Lobby
const downstreamNode = chain[index + 1]; return;
chain.splice(index, 1); // Remove node }
console.log(`Healing "${streamName}": ${upstreamNode} -> ${downstreamNode}`); // Case 2: Tail Left -> Just pop
io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: downstreamNode }); if (index === chain.length - 1) {
chain.pop();
const newTail = chain[chain.length - 1];
if (newTail) io.to(newTail).emit('disconnect_downstream');
}
// Case 3: Middle Left -> Stitch
else {
const upstreamNode = chain[index - 1];
const downstreamNode = chain[index + 1];
chain.splice(index, 1); // Remove node
setTimeout(() => { console.log(`Healing "${streamName}": ${upstreamNode} -> ${downstreamNode}`);
if (streams[streamName] && streams[streamName][0]) { io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: downstreamNode });
io.to(streams[streamName][0]).emit('request_keyframe');
}
}, 2000);
}
delete socketStreamMap[socket.id]; setTimeout(() => {
}); if (streams[streamName] && streams[streamName][0]) {
io.to(streams[streamName][0]).emit('request_keyframe');
}
}, 2000);
}
socket.on('join_monitor', () => { delete socketStreamMap[socket.id];
socket.join('monitors'); });
// Send immediate state
socket.emit('monitor_update', { streams, scores }); socket.on('join_monitor', () => {
}); socket.join('monitors');
// Send immediate state
socket.emit('monitor_update', { streams, scores, metrics });
});
}); });
// 2. Broadcast State to Monitors (1Hz) // 2. Broadcast State to Monitors (1Hz)
// We send the full topology and health scores every second. // We send the full topology and health scores every second.
setInterval(() => { setInterval(() => {
// Only emit if there is someone watching to save bandwidth // Only emit if there is someone watching to save bandwidth
const monitorRoom = io.sockets.adapter.rooms.get('monitors'); const monitorRoom = io.sockets.adapter.rooms.get('monitors');
if (monitorRoom && monitorRoom.size > 0) { if (monitorRoom && monitorRoom.size > 0) {
io.to('monitors').emit('monitor_update', { streams, scores }); io.to('monitors').emit('monitor_update', { streams, scores, metrics });
} }
}, 1000); }, 1000);
// --- THE MULTI-STREAM OPTIMIZER --- // --- THE MULTI-STREAM OPTIMIZER ---
setInterval(() => { setInterval(() => {
// Loop through EVERY active stream // Loop through EVERY active stream
Object.keys(streams).forEach(streamName => { Object.keys(streams).forEach((streamName) => {
const chain = streams[streamName]; const chain = streams[streamName];
if (chain.length < 3) return; if (chain.length < 3) return;
// Scan this specific chain // Scan this specific chain
for (let i = 1; i < chain.length - 1; i++) { for (let i = 1; i < chain.length - 1; i++) {
const current = chain[i]; const current = chain[i];
const next = chain[i + 1]; const next = chain[i + 1];
const scoreCurrent = scores[current] || 0; const scoreCurrent = scores[current] || 0;
const scoreNext = scores[next] || 0; const scoreNext = scores[next] || 0;
if (scoreNext > scoreCurrent + 15) { if (scoreNext > scoreCurrent + 15) {
console.log(`[${streamName}] Swapping ${current} (${scoreCurrent}) with ${next} (${scoreNext})`); console.log(`[${streamName}] Swapping ${current} (${scoreCurrent}) with ${next} (${scoreNext})`);
performSwap(chain, i, i + 1); performSwap(chain, i, i + 1);
break; // One swap per stream per cycle break; // One swap per stream per cycle
} }
} }
}); });
}, 10000); }, 10000);
function performSwap(chain, indexA, indexB) { function performSwap(chain, indexA, indexB) {
const nodeA = chain[indexA]; const nodeA = chain[indexA];
const nodeB = chain[indexB]; const nodeB = chain[indexB];
chain[indexA] = nodeB; chain[indexA] = nodeB;
chain[indexB] = nodeA; chain[indexB] = nodeA;
const upstreamNode = chain[indexA - 1]; const upstreamNode = chain[indexA - 1];
const downstreamNode = chain[indexB + 1]; const downstreamNode = chain[indexB + 1];
if (upstreamNode) io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: nodeB }); if (upstreamNode) io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: nodeB });
io.to(nodeB).emit('connect_to_downstream', { downstreamId: nodeA }); io.to(nodeB).emit('connect_to_downstream', { downstreamId: nodeA });
if (downstreamNode) { if (downstreamNode) {
io.to(nodeA).emit('connect_to_downstream', { downstreamId: downstreamNode }); io.to(nodeA).emit('connect_to_downstream', { downstreamId: downstreamNode });
} else { } else {
io.to(nodeA).emit('disconnect_downstream'); io.to(nodeA).emit('disconnect_downstream');
} }
// Request Keyframe from Head // Request Keyframe from Head
setTimeout(() => { setTimeout(() => {
if (chain[0]) io.to(chain[0]).emit('request_keyframe'); if (chain[0]) io.to(chain[0]).emit('request_keyframe');
}, 1000); }, 1000);
setTimeout(() => { setTimeout(() => {
if (chain[0]) io.to(chain[0]).emit('request_keyframe'); if (chain[0]) io.to(chain[0]).emit('request_keyframe');
}, 4000); }, 4000);
} }
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`)); server.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));