GCX / server.js
veltrixcode's picture
Update server.js
1cf4f19 verified
Raw History Blame
15.7 kB
import express from "express";
import { createServer } from "http";
import { WebSocketServer } from "ws";
const app = express();
app.use(express.json());
console.log("πŸš€ Starting WebSocket streaming server...");
// Store active streams
const streams = new Map(); // streamId -> { publisher: ws, viewers: Set<ws>, metadata }
let currentStream = null;
// Middleware for logging
app.use((req, res, next) => {
console.log(`πŸ“¨ ${req.method} ${req.path} - ${new Date().toISOString()}`);
next();
});
// Root route - Viewer
app.get("/", (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Stream Viewer</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
max-width: 900px;
width: 100%;
}
h1 { color: #333; margin-bottom: 10px; font-size: 2em; }
.status {
padding: 12px 20px;
border-radius: 8px;
margin: 20px 0;
font-weight: 600;
}
.status.waiting { background: #fff3cd; color: #856404; }
.status.live { background: #d4edda; color: #155724; }
.status.error { background: #f8d7da; color: #721c24; }
video {
width: 100%;
border-radius: 12px;
background: #000;
margin: 20px 0;
max-height: 500px;
}
button {
background: #667eea;
color: white;
border: none;
padding: 12px 30px;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
}
button:hover { background: #5568d3; }
button:disabled { background: #ccc; cursor: not-allowed; }
</style>
</head>
<body>
<div class="container">
<h1>πŸ“‘ Live Stream Viewer</h1>
<div id="status" class="status waiting">Waiting for stream...</div>
<video id="video" autoplay playsinline controls muted></video>
<button id="playBtn" onclick="startViewing()">▢️ Start Viewing</button>
<div style="margin-top: 20px; font-size: 14px; color: #666;">
<strong>Publisher:</strong> <a href="/publish" target="_blank">Click here to stream</a>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
const video = document.getElementById('video');
const status = document.getElementById('status');
const playBtn = document.getElementById('playBtn');
let ws = null;
let mediaSource = null;
let sourceBuffer = null;
let queue = [];
async function startViewing() {
try {
status.className = 'status waiting';
status.textContent = 'Connecting...';
playBtn.disabled = true;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = \`\${protocol}//\${window.location.host}/stream\`;
ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
ws.onopen = () => {
console.log('βœ… WebSocket connected');
ws.send(JSON.stringify({ type: 'viewer' }));
};
ws.onmessage = async (event) => {
if (typeof event.data === 'string') {
const msg = JSON.parse(event.data);
if (msg.type === 'stream_available') {
status.className = 'status live';
status.textContent = 'πŸ”΄ LIVE';
} else if (msg.type === 'no_stream') {
status.className = 'status waiting';
status.textContent = 'Waiting for stream...';
} else if (msg.type === 'init') {
// Initialize MediaSource with codec info
if ('MediaSource' in window) {
setupMediaSource(msg.codec);
} else {
// Fallback to simple blob URL for older browsers
setupBlobPlayback();
}
}
} else {
// Binary video data
if (sourceBuffer && !sourceBuffer.updating) {
try {
sourceBuffer.appendBuffer(event.data);
} catch (e) {
queue.push(event.data);
}
} else {
queue.push(event.data);
}
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
status.className = 'status error';
status.textContent = '❌ Connection error';
};
ws.onclose = () => {
console.log('WebSocket closed');
status.className = 'status waiting';
status.textContent = 'Disconnected';
playBtn.disabled = false;
};
} catch (error) {
console.error('Error:', error);
status.className = 'status error';
status.textContent = '❌ ' + error.message;
playBtn.disabled = false;
}
}
function setupMediaSource(codec) {
mediaSource = new MediaSource();
video.src = URL.createObjectURL(mediaSource);
mediaSource.addEventListener('sourceopen', () => {
console.log('MediaSource opened');
try {
sourceBuffer = mediaSource.addSourceBuffer(codec || 'video/webm; codecs="vp8,opus"');
sourceBuffer.addEventListener('updateend', () => {
if (queue.length > 0 && !sourceBuffer.updating) {
const data = queue.shift();
try {
sourceBuffer.appendBuffer(data);
} catch (e) {
console.error('Error appending buffer:', e);
}
}
});
} catch (e) {
console.error('Error creating source buffer:', e);
setupBlobPlayback();
}
});
}
function setupBlobPlayback() {
console.log('Using blob playback fallback');
// Simple fallback - just update video source periodically
}
</script>
</body>
</html>
`);
});
// Publisher route
app.get("/publish", (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stream Publisher</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.container {
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
padding: 40px;
max-width: 800px;
width: 100%;
}
h1 { color: #333; margin-bottom: 20px; font-size: 2em; }
video {
width: 100%;
border-radius: 12px;
background: #000;
margin: 20px 0;
max-height: 400px;
}
.controls {
display: flex;
gap: 10px;
margin: 20px 0;
}
button {
background: #f5576c;
color: white;
border: none;
padding: 12px 30px;
border-radius: 8px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
flex: 1;
}
button:hover { background: #e04556; }
button:disabled { background: #ccc; cursor: not-allowed; }
button.secondary { background: #6c757d; }
.status {
padding: 12px 20px;
border-radius: 8px;
margin: 20px 0;
font-weight: 600;
}
.status.idle { background: #f8f9fa; color: #6c757d; }
.status.streaming { background: #d4edda; color: #155724; }
.status.error { background: #f8d7da; color: #721c24; }
select {
padding: 10px;
border-radius: 8px;
border: 2px solid #ddd;
font-size: 14px;
flex: 1;
}
</style>
</head>
<body>
<div class="container">
<h1>πŸ“Ή Stream Publisher</h1>
<div id="status" class="status idle">Ready to stream</div>
<video id="preview" autoplay muted playsinline></video>
<div class="controls">
<select id="sourceType">
<option value="camera">Camera</option>
<option value="screen">Screen Share</option>
</select>
<button id="startBtn" onclick="startStream()">πŸ”΄ Start</button>
<button id="stopBtn" onclick="stopStream()" disabled class="secondary">⏹ Stop</button>
</div>
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; font-size: 14px; color: #666;">
View stream at: <a href="/" target="_blank">Viewer Page</a>
</div>
</div>
<script>
let stream = null;
let ws = null;
let mediaRecorder = null;
const status = document.getElementById('status');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
async function startStream() {
try {
status.className = 'status idle';
status.textContent = 'Getting media...';
startBtn.disabled = true;
const sourceType = document.getElementById('sourceType').value;
if (sourceType === 'camera') {
stream = await navigator.mediaDevices.getUserMedia({
video: { width: 1280, height: 720 },
audio: true
});
} else {
stream = await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
});
}
document.getElementById('preview').srcObject = stream;
status.textContent = 'Connecting to server...';
// Connect WebSocket
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = \`\${protocol}//\${window.location.host}/stream\`;
ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
ws.onopen = () => {
console.log('βœ… WebSocket connected');
ws.send(JSON.stringify({
type: 'publisher',
codec: 'video/webm; codecs="vp8,opus"'
}));
// Start recording and streaming
const options = {
mimeType: 'video/webm;codecs=vp8,opus',
videoBitsPerSecond: 2500000
};
mediaRecorder = new MediaRecorder(stream, options);
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0 && ws.readyState === WebSocket.OPEN) {
ws.send(event.data);
}
};
mediaRecorder.start(100); // Send chunks every 100ms
status.className = 'status streaming';
status.textContent = 'πŸ”΄ STREAMING LIVE';
stopBtn.disabled = false;
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
status.className = 'status error';
status.textContent = '❌ Connection error';
startBtn.disabled = false;
if (stream) stream.getTracks().forEach(t => t.stop());
};
ws.onclose = () => {
console.log('WebSocket closed');
};
} catch (error) {
console.error('Error:', error);
status.className = 'status error';
status.textContent = '❌ ' + error.message;
startBtn.disabled = false;
if (stream) stream.getTracks().forEach(t => t.stop());
}
}
function stopStream() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
if (ws) {
ws.close();
}
if (stream) {
stream.getTracks().forEach(t => t.stop());
}
stream = null;
document.getElementById('preview').srcObject = null;
status.className = 'status idle';
status.textContent = 'Stopped';
startBtn.disabled = false;
stopBtn.disabled = true;
}
</script>
</body>
</html>
`);
});
// Status endpoint
app.get("/status", (req, res) => {
res.json({
hasStream: currentStream !== null,
viewers: currentStream ? currentStream.viewers.size : 0,
streams: streams.size
});
});
// Create HTTP server
const server = createServer(app);
// Create WebSocket server
const wss = new WebSocketServer({
server,
path: '/stream'
});
wss.on('connection', (ws, req) => {
console.log('πŸ”Œ New WebSocket connection from', req.socket.remoteAddress);
ws.on('message', (data) => {
try {
// Check if it's a text message (JSON)
if (data.toString().startsWith('{')) {
const message = JSON.parse(data.toString());
if (message.type === 'publisher') {
console.log('πŸ“Ή Publisher connected');
// Create new stream
if (currentStream) {
currentStream.publisher.close();
}
currentStream = {
publisher: ws,
viewers: new Set(),
metadata: { codec: message.codec }
};
// Notify all viewers
currentStream.viewers.forEach(viewer => {
viewer.send(JSON.stringify({
type: 'stream_available',
codec: message.codec
}));
});
ws.on('close', () => {
console.log('πŸ“Ή Publisher disconnected');
if (currentStream && currentStream.publisher === ws) {
currentStream.viewers.forEach(viewer => {
viewer.send(JSON.stringify({ type: 'no_stream' }));
});
currentStream = null;
}
});
} else if (message.type === 'viewer') {
console.log('πŸ‘οΈ Viewer connected');
if (currentStream) {
currentStream.viewers.add(ws);
ws.send(JSON.stringify({
type: 'init',
codec: currentStream.metadata.codec
}));
ws.send(JSON.stringify({ type: 'stream_available' }));
} else {
ws.send(JSON.stringify({ type: 'no_stream' }));
}
ws.on('close', () => {
console.log('πŸ‘οΈ Viewer disconnected');
if (currentStream) {
currentStream.viewers.delete(ws);
}
});
}
} else {
// Binary data (video chunks) from publisher
if (currentStream && currentStream.publisher === ws) {
// Broadcast to all viewers
currentStream.viewers.forEach(viewer => {
if (viewer.readyState === ws.OPEN) {
viewer.send(data);
}
});
}
}
} catch (error) {
console.error('❌ WebSocket message error:', error);
}
});
ws.on('error', (error) => {
console.error('❌ WebSocket error:', error);
});
});
// Start server
const PORT = process.env.PORT || 7860;
server.listen(PORT, () => {
console.log(`\n${"=".repeat(50)}`);
console.log(`πŸŽ‰ Server running on port ${PORT}`);
console.log(`${"=".repeat(50)}`);
console.log(`πŸ“Ί Viewer: http://localhost:${PORT}/`);
console.log(`πŸ“Ή Publisher: http://localhost:${PORT}/publish`);
console.log(`${"=".repeat(50)}\n`);
});