Streams done, Monitoring done, unified UI
This commit is contained in:
parent
7edfc1894d
commit
421b633045
241
public/client.js
241
public/client.js
@ -2,6 +2,10 @@ const socket = io();
|
|||||||
const localVideo = document.getElementById('localVideo');
|
const localVideo = document.getElementById('localVideo');
|
||||||
const remoteVideo = document.getElementById('remoteVideo');
|
const remoteVideo = document.getElementById('remoteVideo');
|
||||||
const statusDiv = document.getElementById('status');
|
const statusDiv = document.getElementById('status');
|
||||||
|
const streamListUl = document.getElementById('streamList');
|
||||||
|
const lobbyView = document.getElementById('lobby-view');
|
||||||
|
const streamView = document.getElementById('stream-view');
|
||||||
|
const streamTitle = document.getElementById('currentStreamTitle');
|
||||||
|
|
||||||
// --- Global State ---
|
// --- Global State ---
|
||||||
let localStream = null;
|
let localStream = null;
|
||||||
@ -10,9 +14,9 @@ let iceServers = [];
|
|||||||
// ACTIVE connections
|
// ACTIVE connections
|
||||||
let currentUpstreamPC = null;
|
let currentUpstreamPC = null;
|
||||||
let currentDownstreamPC = null;
|
let currentDownstreamPC = null;
|
||||||
let downstreamId = null; // Socket ID of who we are sending to
|
let downstreamId = null;
|
||||||
|
|
||||||
// FADING connections (Garbage bin for smooth transitions)
|
// FADING connections
|
||||||
let oldUpstreamPCs = [];
|
let oldUpstreamPCs = [];
|
||||||
let oldDownstreamPCs = [];
|
let oldDownstreamPCs = [];
|
||||||
|
|
||||||
@ -22,46 +26,116 @@ async function init() {
|
|||||||
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;
|
iceServers = data.iceServers;
|
||||||
console.log("Loaded ICE Servers");
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Using public STUN");
|
|
||||||
iceServers = [{ urls: 'stun:stun.l.google.com:19302' }];
|
iceServers = [{ urls: 'stun:stun.l.google.com:19302' }];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
init();
|
init();
|
||||||
|
|
||||||
// --- 2. User Actions ---
|
// --- 2. Lobby Logic ---
|
||||||
async function startStream() {
|
|
||||||
try {
|
// Receive list of streams from server
|
||||||
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
|
socket.on('stream_list_update', (streams) => {
|
||||||
localVideo.srcObject = localStream;
|
streamListUl.innerHTML = "";
|
||||||
remoteVideo.style.display = 'none'; // Head doesn't need remote view
|
if (streams.length === 0) {
|
||||||
|
streamListUl.innerHTML = "<li style='cursor:default; color:#777;'>No active streams. Start one!</li>";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
streams.forEach(name => {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerText = `${name}`;
|
||||||
|
li.onclick = () => joinStream(name);
|
||||||
|
streamListUl.appendChild(li);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
async function startStream() {
|
||||||
|
const name = document.getElementById('streamNameInput').value;
|
||||||
|
const fileInput = document.getElementById('videoFileInput');
|
||||||
|
const file = fileInput.files[0];
|
||||||
|
|
||||||
|
if (!name) return alert("Please enter a name");
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (file) {
|
||||||
|
// --- OPTION A: VIDEO FILE MODE ---
|
||||||
|
console.log("Starting stream from video file...");
|
||||||
|
|
||||||
|
// 1. Create a URL for the local file
|
||||||
|
const fileURL = URL.createObjectURL(file);
|
||||||
|
|
||||||
|
// 2. Set it to the local video element
|
||||||
|
localVideo.src = fileURL;
|
||||||
|
localVideo.loop = true; // <--- HERE IS THE LOOP LOGIC
|
||||||
|
localVideo.muted = false; // Must be unmuted to capture audio, use headphones!
|
||||||
|
localVideo.volume = 1.0;
|
||||||
|
|
||||||
|
// 3. Play the video (required before capturing)
|
||||||
|
await localVideo.play();
|
||||||
|
|
||||||
|
// 4. Capture the stream from the video element
|
||||||
|
// (Chrome/Edge use captureStream, Firefox uses mozCaptureStream)
|
||||||
|
if (localVideo.captureStream) {
|
||||||
|
localStream = localVideo.captureStream();
|
||||||
|
} else if (localVideo.mozCaptureStream) {
|
||||||
|
localStream = localVideo.mozCaptureStream();
|
||||||
|
} else {
|
||||||
|
return alert("Your browser does not support capturing video from files.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: captureStream() sometimes doesn't capture audio if the element is muted.
|
||||||
|
// 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: 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}`;
|
||||||
|
|
||||||
|
socket.emit('start_stream', name);
|
||||||
|
statusDiv.innerText = `Status: Broadcasting (Head) | ID: ${socket.id}`;
|
||||||
|
|
||||||
socket.emit('start_stream');
|
|
||||||
statusDiv.innerText = "Status: Broadcasting (Head)";
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Error accessing media:", err);
|
console.error(err);
|
||||||
alert("Could not access camera.");
|
alert("Failed to start stream: " + err.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function joinStream() {
|
function joinStream(name) {
|
||||||
socket.emit('join_stream');
|
// UI Switch
|
||||||
localVideo.style.display = 'none'; // Nodes don't see themselves
|
lobbyView.style.display = 'none';
|
||||||
statusDiv.innerText = "Status: Joining chain...";
|
streamView.style.display = 'block';
|
||||||
|
localVideo.style.display = 'none'; // Viewers don't see themselves
|
||||||
|
streamTitle.innerText = `Watching: ${name}`;
|
||||||
|
|
||||||
|
socket.emit('join_stream', name);
|
||||||
|
statusDiv.innerText = `Status: Joining chain... | ID: ${socket.id}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 3. Health Reporting (The "Bubble Sort" Logic) ---
|
function leaveStream() {
|
||||||
|
location.reload(); // Simple way to reset state and go back to lobby
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// --- 3. Health Reporting (Unchanged) ---
|
||||||
setInterval(calculateAndReportHealth, 5000);
|
setInterval(calculateAndReportHealth, 5000);
|
||||||
|
|
||||||
async function calculateAndReportHealth() {
|
async function calculateAndReportHealth() {
|
||||||
// If I am Head, I am perfect.
|
|
||||||
if (localStream) {
|
if (localStream) {
|
||||||
socket.emit('update_score', 100);
|
socket.emit('update_score', 100);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If I'm not connected, I'm waiting.
|
|
||||||
if (!currentUpstreamPC) return;
|
if (!currentUpstreamPC) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -81,186 +155,135 @@ async function calculateAndReportHealth() {
|
|||||||
const totalPackets = packetsReceived + packetsLost;
|
const totalPackets = packetsReceived + packetsLost;
|
||||||
if (totalPackets === 0) return;
|
if (totalPackets === 0) return;
|
||||||
|
|
||||||
// Calculate Score (0-100)
|
|
||||||
// Heavy penalty for loss, mild for jitter
|
|
||||||
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) {
|
|
||||||
// console.error("Stats error", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 4. Socket Events ---
|
// --- 4. Socket Events (Logic Updated for Smart Disconnect) ---
|
||||||
|
|
||||||
// Instruction: Connect to a new node downstream
|
|
||||||
socket.on('connect_to_downstream', async ({ downstreamId: targetId }) => {
|
socket.on('connect_to_downstream', async ({ downstreamId: targetId }) => {
|
||||||
console.log(`Instruction: Connect downstream to ${targetId}`);
|
|
||||||
downstreamId = targetId;
|
downstreamId = targetId;
|
||||||
await setupDownstreamConnection(targetId);
|
await setupDownstreamConnection(targetId);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Instruction: Stop sending downstream (I am now the tail)
|
|
||||||
socket.on('disconnect_downstream', () => {
|
socket.on('disconnect_downstream', () => {
|
||||||
console.log("Instruction: Disconnect downstream (Became Tail)");
|
|
||||||
if (currentDownstreamPC) {
|
if (currentDownstreamPC) {
|
||||||
currentDownstreamPC.close();
|
currentDownstreamPC.close();
|
||||||
currentDownstreamPC = null;
|
currentDownstreamPC = null;
|
||||||
downstreamId = null;
|
downstreamId = null;
|
||||||
}
|
}
|
||||||
// Also clean up garbage bin
|
|
||||||
oldDownstreamPCs.forEach(pc => pc.close());
|
oldDownstreamPCs.forEach(pc => pc.close());
|
||||||
oldDownstreamPCs = [];
|
oldDownstreamPCs = [];
|
||||||
});
|
});
|
||||||
|
|
||||||
// Signaling Router
|
|
||||||
socket.on('signal_msg', async ({ sender, type, sdp, candidate }) => {
|
socket.on('signal_msg', async ({ sender, type, sdp, candidate }) => {
|
||||||
// A. OFFERS (Always come from Upstream)
|
|
||||||
if (type === 'offer') {
|
if (type === 'offer') {
|
||||||
await handleUpstreamOffer(sender, sdp);
|
await handleUpstreamOffer(sender, sdp);
|
||||||
}
|
} else if (type === 'answer') {
|
||||||
|
|
||||||
// B. ANSWERS (Always come from Downstream)
|
|
||||||
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') {
|
||||||
|
|
||||||
// C. CANDIDATES (Could be for anyone)
|
|
||||||
else if (type === 'candidate') {
|
|
||||||
const ice = new RTCIceCandidate(candidate);
|
const ice = new RTCIceCandidate(candidate);
|
||||||
|
if (currentDownstreamPC && sender === downstreamId) currentDownstreamPC.addIceCandidate(ice).catch(e => { });
|
||||||
// Try Active Downstream
|
if (currentUpstreamPC) currentUpstreamPC.addIceCandidate(ice).catch(e => { });
|
||||||
if (currentDownstreamPC && sender === downstreamId) {
|
|
||||||
currentDownstreamPC.addIceCandidate(ice).catch(e => { });
|
|
||||||
}
|
|
||||||
// Try Active Upstream
|
|
||||||
if (currentUpstreamPC) {
|
|
||||||
currentUpstreamPC.addIceCandidate(ice).catch(e => { });
|
|
||||||
}
|
|
||||||
// Try Fading Connections (Crucial for smooth swap!)
|
|
||||||
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) => alert(msg));
|
socket.on('error_msg', (msg) => {
|
||||||
socket.on('request_keyframe', () => console.log("Keyframe requested by network"));
|
alert(msg);
|
||||||
socket.on('stream_ended', () => {
|
|
||||||
alert("Stream ended");
|
|
||||||
location.reload();
|
location.reload();
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- 5. WebRTC Logic (Make-Before-Break) ---
|
socket.on('stream_ended', () => {
|
||||||
|
alert("Stream ended by host");
|
||||||
|
location.reload();
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('request_keyframe', () => {
|
||||||
|
console.log("Network requested keyframe");
|
||||||
|
// If we were using Insertable streams, we'd need to handle this.
|
||||||
|
// With Standard API, the browser handles PLI automatically.
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- 5. WebRTC Logic (Merged Smart Disconnect) ---
|
||||||
|
|
||||||
// --- UPSTREAM Handling (Receiving) ---
|
|
||||||
async function handleUpstreamOffer(senderId, sdp) {
|
async function handleUpstreamOffer(senderId, sdp) {
|
||||||
console.log(`Negotiating new Upstream connection from ${senderId}`);
|
|
||||||
|
|
||||||
const newPC = new RTCPeerConnection({ iceServers });
|
const newPC = new RTCPeerConnection({ iceServers });
|
||||||
|
|
||||||
|
// Safety: If connection hangs, kill old one eventually
|
||||||
|
let safetyTimer = setTimeout(() => {
|
||||||
|
if (currentUpstreamPC && currentUpstreamPC !== newPC) {
|
||||||
|
currentUpstreamPC.close();
|
||||||
|
}
|
||||||
|
}, 15000);
|
||||||
|
|
||||||
newPC.ontrack = (event) => {
|
newPC.ontrack = (event) => {
|
||||||
console.log(`New Upstream Track (${event.track.kind}) Active.`);
|
clearTimeout(safetyTimer); // Success!
|
||||||
|
|
||||||
// A. Update Screen (Idempotent: doing this twice is fine)
|
|
||||||
remoteVideo.srcObject = event.streams[0];
|
remoteVideo.srcObject = event.streams[0];
|
||||||
statusDiv.innerText = "Status: Connected (Stable)";
|
statusDiv.innerText = `Status: Connected | ID: ${socket.id}`;
|
||||||
|
|
||||||
// B. Hot-Swap the Relay
|
|
||||||
if (currentDownstreamPC) {
|
if (currentDownstreamPC) {
|
||||||
const sender = currentDownstreamPC.getSenders().find(s => s.track && s.track.kind === event.track.kind);
|
const sender = currentDownstreamPC.getSenders().find(s => s.track && s.track.kind === event.track.kind);
|
||||||
if (sender) {
|
if (sender) sender.replaceTrack(event.track);
|
||||||
sender.replaceTrack(event.track);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// C. Retire the OLD connection (THE FIX IS HERE)
|
// Smart Disconnect: Old connection dies immediately upon success
|
||||||
// We only queue the old PC if it exists AND it isn't the one we just created.
|
|
||||||
if (currentUpstreamPC && currentUpstreamPC !== newPC) {
|
if (currentUpstreamPC && currentUpstreamPC !== newPC) {
|
||||||
const oldPC = currentUpstreamPC;
|
const oldPC = currentUpstreamPC;
|
||||||
oldUpstreamPCs.push(oldPC);
|
|
||||||
|
|
||||||
console.log("Queueing old upstream connection for death in 4s...");
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
oldPC.close();
|
oldPC.close();
|
||||||
// Remove from garbage bin
|
|
||||||
oldUpstreamPCs = oldUpstreamPCs.filter(pc => pc !== oldPC);
|
oldUpstreamPCs = oldUpstreamPCs.filter(pc => pc !== oldPC);
|
||||||
console.log("Closed old upstream connection.");
|
}, 1000);
|
||||||
}, 4000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// D. Set New as Current
|
|
||||||
currentUpstreamPC = newPC;
|
currentUpstreamPC = newPC;
|
||||||
};
|
};
|
||||||
|
|
||||||
newPC.onicecandidate = (event) => {
|
newPC.onicecandidate = (event) => {
|
||||||
if (event.candidate) {
|
if (event.candidate) socket.emit('signal_msg', { target: senderId, type: 'candidate', candidate: event.candidate });
|
||||||
socket.emit('signal_msg', { target: senderId, type: 'candidate', candidate: event.candidate });
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await newPC.setRemoteDescription(new RTCSessionDescription(sdp));
|
await newPC.setRemoteDescription(new RTCSessionDescription(sdp));
|
||||||
const answer = await newPC.createAnswer();
|
const answer = await newPC.createAnswer();
|
||||||
await newPC.setLocalDescription(answer);
|
await newPC.setLocalDescription(answer);
|
||||||
|
|
||||||
socket.emit('signal_msg', { target: senderId, type: 'answer', sdp: answer });
|
socket.emit('signal_msg', { target: senderId, type: 'answer', sdp: answer });
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- DOWNSTREAM Handling (Sending) ---
|
|
||||||
async function setupDownstreamConnection(targetId) {
|
async function setupDownstreamConnection(targetId) {
|
||||||
console.log(`Setting up downstream to ${targetId}`);
|
|
||||||
|
|
||||||
// 1. Retire existing downstream (Fade Out)
|
|
||||||
if (currentDownstreamPC) {
|
if (currentDownstreamPC) {
|
||||||
console.log("Moving current downstream to background (Overlap Mode)");
|
|
||||||
const oldPC = currentDownstreamPC;
|
const oldPC = currentDownstreamPC;
|
||||||
oldDownstreamPCs.push(oldPC);
|
oldDownstreamPCs.push(oldPC);
|
||||||
|
|
||||||
// Keep sending for 5 seconds so they have time to connect to their NEW source
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
oldPC.close();
|
oldPC.close();
|
||||||
oldDownstreamPCs = oldDownstreamPCs.filter(pc => pc !== oldPC);
|
oldDownstreamPCs = oldDownstreamPCs.filter(pc => pc !== oldPC);
|
||||||
console.log("Closed old downstream connection");
|
|
||||||
}, 5000);
|
}, 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Create NEW downstream
|
|
||||||
currentDownstreamPC = new RTCPeerConnection({ iceServers });
|
currentDownstreamPC = new RTCPeerConnection({ iceServers });
|
||||||
|
|
||||||
// 3. Add Tracks
|
|
||||||
if (localStream) {
|
if (localStream) {
|
||||||
// Head: Send Camera
|
|
||||||
localStream.getTracks().forEach(track => currentDownstreamPC.addTrack(track, localStream));
|
localStream.getTracks().forEach(track => currentDownstreamPC.addTrack(track, localStream));
|
||||||
} else if (currentUpstreamPC) {
|
} else if (currentUpstreamPC) {
|
||||||
// Relay: Send what we are receiving
|
|
||||||
currentUpstreamPC.getReceivers().forEach(receiver => {
|
currentUpstreamPC.getReceivers().forEach(receiver => {
|
||||||
if (receiver.track) {
|
if (receiver.track) currentDownstreamPC.addTrack(receiver.track, remoteVideo.srcObject);
|
||||||
// "remoteVideo.srcObject" ensures stream ID consistency
|
|
||||||
currentDownstreamPC.addTrack(receiver.track, remoteVideo.srcObject);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
currentDownstreamPC.onicecandidate = (event) => {
|
currentDownstreamPC.onicecandidate = (event) => {
|
||||||
if (event.candidate) {
|
if (event.candidate) socket.emit('signal_msg', { target: targetId, type: 'candidate', candidate: event.candidate });
|
||||||
socket.emit('signal_msg', { target: targetId, type: 'candidate', candidate: event.candidate });
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const offer = await currentDownstreamPC.createOffer();
|
const offer = await currentDownstreamPC.createOffer();
|
||||||
|
|
||||||
// 4. BITRATE HACK: Force 4Mbps limit (Standard WebRTC defaults low)
|
|
||||||
offer.sdp = offer.sdp.replace(/b=AS:([0-9]+)/g, 'b=AS:4000');
|
offer.sdp = offer.sdp.replace(/b=AS:([0-9]+)/g, 'b=AS:4000');
|
||||||
if (!offer.sdp.includes('b=AS:')) {
|
if (!offer.sdp.includes('b=AS:')) offer.sdp = offer.sdp.replace(/(m=video.*\r\n)/, '$1b=AS:4000\r\n');
|
||||||
// If no bandwidth line exists, add it to the video section
|
|
||||||
offer.sdp = offer.sdp.replace(/(m=video.*\r\n)/, '$1b=AS:4000\r\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
await currentDownstreamPC.setLocalDescription(offer);
|
await currentDownstreamPC.setLocalDescription(offer);
|
||||||
socket.emit('signal_msg', { target: targetId, type: 'offer', sdp: offer });
|
socket.emit('signal_msg', { target: targetId, type: 'offer', sdp: offer });
|
||||||
|
|||||||
@ -3,50 +3,262 @@
|
|||||||
|
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||||
<title>P2P Daisy Chain Livestream</title>
|
<title>Strandcast</title>
|
||||||
<style>
|
<style>
|
||||||
|
/* --- RESET & BASICS --- */
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||||
background: #111;
|
background: #0a0a0a;
|
||||||
color: #fff;
|
color: #eee;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
video {
|
/* --- NAVIGATION BAR --- */
|
||||||
width: 80%;
|
.navbar {
|
||||||
max-width: 600px;
|
background-color: #111;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
padding: 15px 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar .brand {
|
||||||
|
color: #00d2ff;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: bold;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a {
|
||||||
|
color: #888;
|
||||||
|
text-decoration: none;
|
||||||
|
margin-left: 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a:hover {
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a.active {
|
||||||
|
color: #fff;
|
||||||
|
font-weight: bold;
|
||||||
|
border-bottom: 2px solid #00d2ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- LAYOUT CONTAINERS --- */
|
||||||
|
.container {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
padding: 20px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
font-weight: 300;
|
||||||
|
font-size: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- LOBBY STYLES --- */
|
||||||
|
#lobby-view {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 500px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
background: #161616;
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Stream List */
|
||||||
|
ul {
|
||||||
|
list-style: none;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
li {
|
||||||
|
background: #222;
|
||||||
|
margin: 8px 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:active {
|
||||||
|
background: #333;
|
||||||
|
transform: scale(0.98);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Inputs - 16px font prevents iOS zoom */
|
||||||
|
input[type="text"] {
|
||||||
|
width: 100%;
|
||||||
|
padding: 12px;
|
||||||
background: #000;
|
background: #000;
|
||||||
border: 2px solid #333;
|
border: 1px solid #444;
|
||||||
margin: 10px;
|
color: white;
|
||||||
|
border-radius: 6px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
outline: none;
|
||||||
|
font-size: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.controls {
|
input[type="file"] {
|
||||||
margin: 20px;
|
width: 100%;
|
||||||
|
padding: 10px;
|
||||||
|
background: #222;
|
||||||
|
color: #ccc;
|
||||||
|
border-radius: 6px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
border: 1px solid #333;
|
||||||
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
button {
|
||||||
padding: 10px 20px;
|
width: 100%;
|
||||||
font-size: 16px;
|
padding: 14px;
|
||||||
|
/* Larger tap area */
|
||||||
cursor: pointer;
|
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 {
|
||||||
|
opacity: 0.8;
|
||||||
|
transform: scale(0.98);
|
||||||
|
}
|
||||||
|
|
||||||
|
button.leave-btn {
|
||||||
|
background: #d32f2f;
|
||||||
|
margin-top: 20px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- STREAM VIEW --- */
|
||||||
|
#stream-view {
|
||||||
|
display: none;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
video {
|
||||||
|
width: 100%;
|
||||||
|
/* Maintain aspect ratio */
|
||||||
|
aspect-ratio: 16 / 9;
|
||||||
|
background: #000;
|
||||||
|
border-radius: 8px;
|
||||||
|
margin: 10px 0;
|
||||||
|
object-fit: cover;
|
||||||
}
|
}
|
||||||
|
|
||||||
#status {
|
#status {
|
||||||
color: #0f0;
|
color: #00d2ff;
|
||||||
margin-top: 10px;
|
margin-top: 10px;
|
||||||
|
font-family: monospace;
|
||||||
|
background: #111;
|
||||||
|
display: inline-block;
|
||||||
|
padding: 8px 20px;
|
||||||
|
border-radius: 20px;
|
||||||
|
border: 1px solid #333;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- MOBILE MEDIA QUERY --- */
|
||||||
|
@media (max-width: 600px) {
|
||||||
|
.navbar {
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar .brand {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a {
|
||||||
|
margin: 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
padding: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
padding: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
<h1>Daisy Chain Relay</h1>
|
<nav class="navbar">
|
||||||
<div class="controls">
|
<a href="/" class="brand">Strandcast</a>
|
||||||
<button id="btnStart" onclick="startStream()">Start Stream (As Head)</button>
|
<div class="nav-links">
|
||||||
<button id="btnJoin" onclick="joinStream()">Join Stream (As Node)</button>
|
<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>
|
</div>
|
||||||
<video id="localVideo" autoplay muted playsinline></video>
|
|
||||||
<video id="remoteVideo" autoplay playsinline></video>
|
|
||||||
<div id="status">Status: Disconnected</div>
|
|
||||||
<script src="/socket.io/socket.io.js"></script>
|
<script src="/socket.io/socket.io.js"></script>
|
||||||
<script src="client.js"></script>
|
<script src="client.js"></script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
214
public/monitor.html
Normal file
214
public/monitor.html
Normal file
@ -0,0 +1,214 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<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;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
/* Unified Font Stack */
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||||
|
background: #0a0a0a;
|
||||||
|
color: #eee;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- NAVIGATION BAR --- */
|
||||||
|
.navbar {
|
||||||
|
background-color: #111;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
padding: 15px 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.navbar .brand {
|
||||||
|
color: #00d2ff;
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: bold;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a {
|
||||||
|
color: #888;
|
||||||
|
text-decoration: none;
|
||||||
|
margin-left: 20px;
|
||||||
|
font-size: 14px;
|
||||||
|
padding: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a:hover {
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-links a.active {
|
||||||
|
color: #fff;
|
||||||
|
font-weight: bold;
|
||||||
|
border-bottom: 2px solid #00d2ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- DASHBOARD --- */
|
||||||
|
h1 {
|
||||||
|
text-align: center;
|
||||||
|
margin: 20px 0;
|
||||||
|
font-weight: 300;
|
||||||
|
font-size: 24px;
|
||||||
|
/* Matched to index.html */
|
||||||
|
}
|
||||||
|
|
||||||
|
#dashboard {
|
||||||
|
padding: 10px 20px;
|
||||||
|
flex: 1;
|
||||||
|
overflow-x: hidden;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-container {
|
||||||
|
/* Matched to .card in index.html */
|
||||||
|
background: #161616;
|
||||||
|
border: 1px solid #333;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 20px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.stream-title {
|
||||||
|
color: #00d2ff;
|
||||||
|
font-size: 14px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
font-weight: bold;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
border-bottom: 1px solid #333;
|
||||||
|
padding-bottom: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The scrolling wrapper */
|
||||||
|
.chain-wrapper {
|
||||||
|
overflow-x: auto;
|
||||||
|
-webkit-overflow-scrolling: touch;
|
||||||
|
padding-bottom: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chain-visual {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
width: max-content;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The Nodes */
|
||||||
|
.node {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
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 {
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 4px;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node-score {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.node-role {
|
||||||
|
font-size: 9px;
|
||||||
|
color: #888;
|
||||||
|
text-transform: uppercase;
|
||||||
|
margin-top: 4px;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Health Colors */
|
||||||
|
.healthy {
|
||||||
|
border-color: #00ff88;
|
||||||
|
color: #00ff88;
|
||||||
|
box-shadow: 0 0 10px rgba(0, 255, 136, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.meh {
|
||||||
|
border-color: #ffaa00;
|
||||||
|
color: #ffaa00;
|
||||||
|
}
|
||||||
|
|
||||||
|
.weak {
|
||||||
|
border-color: #ff3333;
|
||||||
|
color: #ff3333;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Arrows */
|
||||||
|
.arrow {
|
||||||
|
font-size: 16px;
|
||||||
|
color: #555;
|
||||||
|
margin: 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- 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>
|
||||||
141
public/monitor.js
Normal file
141
public/monitor.js
Normal file
@ -0,0 +1,141 @@
|
|||||||
|
const socket = io();
|
||||||
|
const dashboard = document.getElementById('dashboard');
|
||||||
|
|
||||||
|
// Identify as a monitor
|
||||||
|
socket.emit('join_monitor');
|
||||||
|
|
||||||
|
socket.on('monitor_update', ({ streams, scores }) => {
|
||||||
|
updateDashboard(streams, scores);
|
||||||
|
});
|
||||||
|
|
||||||
|
function updateDashboard(streams, scores) {
|
||||||
|
const activeStreamNames = Object.keys(streams);
|
||||||
|
|
||||||
|
// 1. Remove streams that no longer exist
|
||||||
|
const existingContainers = document.querySelectorAll('.stream-container');
|
||||||
|
existingContainers.forEach(container => {
|
||||||
|
const name = container.getAttribute('data-stream');
|
||||||
|
if (!streams[name]) {
|
||||||
|
container.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Add or Update streams
|
||||||
|
if (activeStreamNames.length === 0) {
|
||||||
|
// If empty, show message (only if not already showing it)
|
||||||
|
if (!dashboard.innerText.includes("No Active Streams")) {
|
||||||
|
dashboard.innerHTML = "<div style='text-align:center; color:#555; margin-top:50px;'>No Active Streams</div>";
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
// 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 (!dashboard.querySelector('.stream-container')) {
|
||||||
|
dashboard.innerHTML = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
activeStreamNames.forEach(name => {
|
||||||
|
let container = document.getElementById(`stream-${name}`);
|
||||||
|
const chain = streams[name];
|
||||||
|
|
||||||
|
// Create Container if it doesn't exist
|
||||||
|
if (!container) {
|
||||||
|
container = document.createElement('div');
|
||||||
|
container.id = `stream-${name}`;
|
||||||
|
container.className = 'stream-container';
|
||||||
|
container.setAttribute('data-stream', name);
|
||||||
|
|
||||||
|
// Structure
|
||||||
|
const title = document.createElement('div');
|
||||||
|
title.className = 'stream-title';
|
||||||
|
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.className = 'chain-wrapper';
|
||||||
|
|
||||||
|
const visual = document.createElement('div');
|
||||||
|
visual.className = 'chain-visual';
|
||||||
|
|
||||||
|
wrapper.appendChild(visual);
|
||||||
|
container.appendChild(title);
|
||||||
|
container.appendChild(wrapper);
|
||||||
|
dashboard.appendChild(container);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update Title
|
||||||
|
const titleEl = container.querySelector('.stream-title');
|
||||||
|
titleEl.innerText = `Stream: ${name} (${chain.length} nodes)`;
|
||||||
|
|
||||||
|
// Update Nodes
|
||||||
|
updateChainVisual(container.querySelector('.chain-visual'), chain, scores);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateChainVisual(visualContainer, chain, scores) {
|
||||||
|
const existingNodes = Array.from(visualContainer.querySelectorAll('.node-wrapper'));
|
||||||
|
const nodeMap = {};
|
||||||
|
existingNodes.forEach(el => nodeMap[el.getAttribute('data-id')] = el);
|
||||||
|
|
||||||
|
const processedIds = new Set();
|
||||||
|
|
||||||
|
chain.forEach((socketId, index) => {
|
||||||
|
processedIds.add(socketId);
|
||||||
|
|
||||||
|
const score = scores[socketId] !== undefined ? scores[socketId] : '??';
|
||||||
|
let healthClass = 'meh';
|
||||||
|
if (score >= 80) healthClass = 'healthy';
|
||||||
|
if (score < 50) healthClass = 'weak';
|
||||||
|
if (index === 0) healthClass = 'healthy';
|
||||||
|
|
||||||
|
const role = index === 0 ? "SOURCE" : (index === chain.length - 1 ? "VIEWER" : "RELAY");
|
||||||
|
const shortId = socketId.substring(0, 4);
|
||||||
|
|
||||||
|
let nodeWrapper = nodeMap[socketId];
|
||||||
|
|
||||||
|
// --- CREATE ---
|
||||||
|
if (!nodeWrapper) {
|
||||||
|
nodeWrapper = document.createElement('div');
|
||||||
|
nodeWrapper.className = 'node-wrapper';
|
||||||
|
nodeWrapper.setAttribute('data-id', socketId);
|
||||||
|
nodeWrapper.style.display = 'flex';
|
||||||
|
nodeWrapper.style.alignItems = 'center';
|
||||||
|
|
||||||
|
nodeWrapper.innerHTML = `
|
||||||
|
<div class="arrow">➔</div>
|
||||||
|
<div class="node">
|
||||||
|
<div class="node-role"></div>
|
||||||
|
<div class="node-id"></div>
|
||||||
|
<div class="node-score"></div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
visualContainer.appendChild(nodeWrapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- UPDATE ---
|
||||||
|
// 1. Order (Preserve Scroll)
|
||||||
|
if (visualContainer.children[index] !== nodeWrapper) {
|
||||||
|
visualContainer.insertBefore(nodeWrapper, visualContainer.children[index]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Arrow Visibility
|
||||||
|
const arrow = nodeWrapper.querySelector('.arrow');
|
||||||
|
arrow.style.opacity = index === 0 ? "0" : "1";
|
||||||
|
|
||||||
|
// 3. Data
|
||||||
|
const nodeEl = nodeWrapper.querySelector('.node');
|
||||||
|
nodeEl.className = `node ${healthClass}`;
|
||||||
|
|
||||||
|
nodeWrapper.querySelector('.node-role').innerText = role;
|
||||||
|
nodeWrapper.querySelector('.node-id').innerText = shortId;
|
||||||
|
nodeWrapper.querySelector('.node-score').innerText = score;
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- REMOVE ---
|
||||||
|
existingNodes.forEach(el => {
|
||||||
|
const id = el.getAttribute('data-id');
|
||||||
|
if (!processedIds.has(id)) {
|
||||||
|
el.remove();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
230
server.js
230
server.js
@ -21,53 +21,66 @@ app.get('/api/get-turn-credentials', async (req, res) => {
|
|||||||
res.json(response.data);
|
res.json(response.data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Cloudflare Error:", error.message);
|
console.error("Cloudflare Error:", error.message);
|
||||||
res.status(500).json({ error: "Failed to fetch credentials" });
|
res.json({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- Daisy Chain Logic ---
|
// --- STATE MANAGEMENT ---
|
||||||
let strand = []; // Ordered list of socket IDs
|
// Format: { "StreamName": [socketId1, socketId2, ...] }
|
||||||
let scores = {}; // Map: socket.id -> score (0-100)
|
const streams = {};
|
||||||
|
const socketStreamMap = {}; // Helper: socketId -> StreamName (for fast lookups on disconnect)
|
||||||
|
const scores = {}; // socketId -> Health Score (0-100)
|
||||||
|
|
||||||
io.on('connection', (socket) => {
|
io.on('connection', (socket) => {
|
||||||
console.log(`User connected: ${socket.id}`);
|
console.log(`User connected: ${socket.id}`);
|
||||||
|
|
||||||
// Default score for new users (optimistic, so they get a chance to prove themselves)
|
|
||||||
scores[socket.id] = 80;
|
scores[socket.id] = 80;
|
||||||
|
|
||||||
socket.on('update_score', (score) => {
|
// 0. Send the list of streams to the new user
|
||||||
scores[socket.id] = score;
|
socket.emit('stream_list_update', Object.keys(streams));
|
||||||
});
|
|
||||||
|
|
||||||
// A. Start Stream (Head)
|
// A. Start New Stream
|
||||||
socket.on('start_stream', () => {
|
socket.on('start_stream', (streamName) => {
|
||||||
if (strand.length > 0) {
|
if (streams[streamName]) {
|
||||||
socket.emit('error_msg', "Stream already in progress.");
|
socket.emit('error_msg', "Stream name already exists.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
strand.push(socket.id);
|
if (socketStreamMap[socket.id]) {
|
||||||
console.log("Stream started. Head:", socket.id);
|
socket.emit('error_msg', "You are already in a stream.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
streams[streamName] = [socket.id];
|
||||||
|
socketStreamMap[socket.id] = streamName;
|
||||||
|
|
||||||
|
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
|
||||||
|
io.emit('stream_list_update', Object.keys(streams));
|
||||||
});
|
});
|
||||||
|
|
||||||
// B. Join Stream (Tail)
|
// B. Join Existing Stream
|
||||||
socket.on('join_stream', () => {
|
socket.on('join_stream', (streamName) => {
|
||||||
if (strand.length === 0) {
|
const chain = streams[streamName];
|
||||||
socket.emit('error_msg', "No active stream to join.");
|
if (!chain) {
|
||||||
|
socket.emit('error_msg', "Stream does not exist.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const upstreamPeerId = strand[strand.length - 1];
|
const upstreamPeerId = chain[chain.length - 1];
|
||||||
strand.push(socket.id);
|
chain.push(socket.id);
|
||||||
|
socketStreamMap[socket.id] = streamName;
|
||||||
|
|
||||||
console.log(`User ${socket.id} joined. Upstream: ${upstreamPeerId}`);
|
console.log(`User ${socket.id} joined stream "${streamName}". Upstream: ${upstreamPeerId}`);
|
||||||
|
|
||||||
// 1. 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 });
|
||||||
|
|
||||||
// 2. Request Keyframe from Head (Delayed to allow connection setup)
|
// Request Keyframe (Targeting the Head of THIS stream)
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (strand[0]) io.to(strand[0]).emit('request_keyframe');
|
if (streams[streamName] && streams[streamName][0]) {
|
||||||
|
io.to(streams[streamName][0]).emit('request_keyframe');
|
||||||
|
}
|
||||||
}, 2000);
|
}, 2000);
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -76,112 +89,139 @@ io.on('connection', (socket) => {
|
|||||||
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. Keyframe Relay
|
// D. Score Updates
|
||||||
socket.on('relay_keyframe_upstream', () => {
|
socket.on('update_score', (score) => {
|
||||||
// In a real robust app, you'd bubble this up the chain.
|
scores[socket.id] = score;
|
||||||
// Here we just blast the Source directly if we know who they are.
|
|
||||||
if (strand[0]) io.to(strand[0]).emit('request_keyframe');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// E. Disconnects (Healing)
|
// E. Keyframe Relay
|
||||||
|
socket.on('relay_keyframe_upstream', () => {
|
||||||
|
const streamName = socketStreamMap[socket.id];
|
||||||
|
if (streamName && streams[streamName]) {
|
||||||
|
io.to(streams[streamName][0]).emit('request_keyframe');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// F. Disconnects (Healing)
|
||||||
socket.on('disconnect', () => {
|
socket.on('disconnect', () => {
|
||||||
const index = strand.indexOf(socket.id);
|
delete scores[socket.id];
|
||||||
|
const streamName = socketStreamMap[socket.id];
|
||||||
|
|
||||||
|
if (!streamName) return; // User wasn't in a stream
|
||||||
|
|
||||||
|
const chain = streams[streamName];
|
||||||
|
if (!chain) return;
|
||||||
|
|
||||||
|
const index = chain.indexOf(socket.id);
|
||||||
if (index === -1) return;
|
if (index === -1) return;
|
||||||
|
|
||||||
console.log(`User ${socket.id} disconnected. Index: ${index}`);
|
console.log(`User ${socket.id} left stream "${streamName}". Index: ${index}`);
|
||||||
|
|
||||||
// Head left
|
// Case 1: Head Left -> Destroy Stream
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
strand = [];
|
delete streams[streamName];
|
||||||
io.emit('stream_ended');
|
// 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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tail left
|
// Case 2: Tail Left -> Just pop
|
||||||
if (index === strand.length - 1) {
|
if (index === chain.length - 1) {
|
||||||
strand.pop();
|
chain.pop();
|
||||||
return;
|
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
|
||||||
|
|
||||||
|
console.log(`Healing "${streamName}": ${upstreamNode} -> ${downstreamNode}`);
|
||||||
|
io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: downstreamNode });
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (streams[streamName] && streams[streamName][0]) {
|
||||||
|
io.to(streams[streamName][0]).emit('request_keyframe');
|
||||||
|
}
|
||||||
|
}, 2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Middle left (Stitch)
|
delete socketStreamMap[socket.id];
|
||||||
const upstreamNode = strand[index - 1];
|
});
|
||||||
const downstreamNode = strand[index + 1];
|
|
||||||
strand.splice(index, 1);
|
|
||||||
|
|
||||||
console.log(`Healing: ${upstreamNode} -> ${downstreamNode}`);
|
socket.on('join_monitor', () => {
|
||||||
io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: downstreamNode });
|
socket.join('monitors');
|
||||||
|
// Send immediate state
|
||||||
setTimeout(() => {
|
socket.emit('monitor_update', { streams, scores });
|
||||||
if (strand[0]) io.to(strand[0]).emit('request_keyframe');
|
|
||||||
}, 2000);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- THE OPTIMIZER LOOP ---
|
// 2. Broadcast State to Monitors (1Hz)
|
||||||
|
// We send the full topology and health scores every second.
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (strand.length < 3) return; // Need at least Head + 2 Nodes to swap anything
|
// Only emit if there is someone watching to save bandwidth
|
||||||
|
const monitorRoom = io.sockets.adapter.rooms.get('monitors');
|
||||||
|
if (monitorRoom && monitorRoom.size > 0) {
|
||||||
|
io.to('monitors').emit('monitor_update', { streams, scores });
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
// We iterate from the 2nd node (Index 1) to the end.
|
// --- THE MULTI-STREAM OPTIMIZER ---
|
||||||
// Index 0 is HEAD (Source), we never move the source.
|
setInterval(() => {
|
||||||
let swapped = false;
|
// Loop through EVERY active stream
|
||||||
|
Object.keys(streams).forEach(streamName => {
|
||||||
|
const chain = streams[streamName];
|
||||||
|
|
||||||
// We look for ONE swap per cycle to minimize chaos.
|
if (chain.length < 3) return;
|
||||||
for (let i = 1; i < strand.length - 1; i++) {
|
|
||||||
const current = strand[i];
|
|
||||||
const next = strand[i + 1];
|
|
||||||
|
|
||||||
const scoreCurrent = scores[current] || 0;
|
// Scan this specific chain
|
||||||
const scoreNext = scores[next] || 0;
|
for (let i = 1; i < chain.length - 1; i++) {
|
||||||
|
const current = chain[i];
|
||||||
|
const next = chain[i + 1];
|
||||||
|
|
||||||
// THRESHOLD: Only swap if the next guy is significantly stronger (+15 points)
|
const scoreCurrent = scores[current] || 0;
|
||||||
// This prevents users flip-flopping constantly due to minor fluctuations.
|
const scoreNext = scores[next] || 0;
|
||||||
if (scoreNext > scoreCurrent + 15) {
|
|
||||||
console.log(`Swapping Weak ${current} (${scoreCurrent}) with Strong ${next} (${scoreNext})`);
|
|
||||||
|
|
||||||
performSwap(i, i + 1);
|
if (scoreNext > scoreCurrent + 15) {
|
||||||
swapped = true;
|
console.log(`[${streamName}] Swapping ${current} (${scoreCurrent}) with ${next} (${scoreNext})`);
|
||||||
break; // Stop after one swap to let network settle
|
performSwap(chain, i, i + 1);
|
||||||
|
break; // One swap per stream per cycle
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
}, 10000); // Run every 10 seconds
|
}, 10000);
|
||||||
|
|
||||||
function performSwap(indexA, indexB) {
|
function performSwap(chain, indexA, indexB) {
|
||||||
// 1. Update the Array (Logical Swap)
|
const nodeA = chain[indexA];
|
||||||
const nodeA = strand[indexA];
|
const nodeB = chain[indexB];
|
||||||
const nodeB = strand[indexB];
|
chain[indexA] = nodeB;
|
||||||
strand[indexA] = nodeB;
|
chain[indexB] = nodeA;
|
||||||
strand[indexB] = nodeA;
|
|
||||||
|
|
||||||
// State after swap:
|
const upstreamNode = chain[indexA - 1];
|
||||||
// [ ... -> Upstream -> NodeB -> NodeA -> Downstream -> ... ]
|
const downstreamNode = chain[indexB + 1];
|
||||||
|
|
||||||
// Identify the relevant neighbors
|
if (upstreamNode) io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: nodeB });
|
||||||
const upstreamNode = strand[indexA - 1]; // The node before the pair
|
|
||||||
const downstreamNode = strand[indexB + 1]; // The node after the pair
|
|
||||||
|
|
||||||
// 2. Instruct the Upstream to connect to the NEW first node (NodeB)
|
|
||||||
if (upstreamNode) {
|
|
||||||
io.to(upstreamNode).emit('connect_to_downstream', { downstreamId: nodeB });
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Instruct NodeB to connect to NodeA (The internal link)
|
|
||||||
io.to(nodeB).emit('connect_to_downstream', { downstreamId: nodeA });
|
io.to(nodeB).emit('connect_to_downstream', { downstreamId: nodeA });
|
||||||
|
|
||||||
// 4. Instruct NodeA to connect to the Downstream (or null if end)
|
|
||||||
if (downstreamNode) {
|
if (downstreamNode) {
|
||||||
io.to(nodeA).emit('connect_to_downstream', { downstreamId: downstreamNode });
|
io.to(nodeA).emit('connect_to_downstream', { downstreamId: downstreamNode });
|
||||||
} else {
|
} else {
|
||||||
// If NodeA is now the tail, it disconnects its downstream
|
io.to(nodeA).emit('disconnect_downstream');
|
||||||
io.to(nodeA).emit('disconnect_downstream'); // You might need to add this handler to client
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Trigger Keyframes to heal the image
|
// Request Keyframe from Head
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (strand[0]) io.to(strand[0]).emit('request_keyframe');
|
if (chain[0]) io.to(chain[0]).emit('request_keyframe');
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
setTimeout(() => {
|
||||||
|
if (chain[0]) io.to(chain[0]).emit('request_keyframe');
|
||||||
|
}, 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}`));
|
||||||
Loading…
x
Reference in New Issue
Block a user