Spaces:
Paused
Paused
Download server.js from veltrixcode/GCX: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/spaces/veltrixcode/GCX/resolve/7c5ccdfeb877a144575c6498df7fedec95c144d5/server.js
- Command line
-
hf download hf://spaces/veltrixcode/GCX@7c5ccdfeb877a144575c6498df7fedec95c144d5/server.js
-
curl -L -o server.js https://huggingface.co/spaces/veltrixcode/GCX/resolve/7c5ccdfeb877a144575c6498df7fedec95c144d5/server.js
20 kB
| import express from "express"; | |
| import http from "http"; | |
| import mediasoup from "mediasoup"; | |
| import cors from "cors"; | |
| const app = express(); | |
| app.use(cors()); | |
| app.use(express.text({ type: 'application/sdp' })); | |
| app.use(express.json()); | |
| console.log("π Starting mediasoup WHIP/WHEP server..."); | |
| // Get announced IP from environment or use public IP detection | |
| const ANNOUNCED_IP = process.env.ANNOUNCED_IP || null; | |
| // Create mediasoup worker | |
| const worker = await mediasoup.createWorker({ | |
| logLevel: "warn", | |
| rtcMinPort: 10000, | |
| rtcMaxPort: 10100, | |
| }); | |
| console.log("β mediasoup worker created [pid:%d]", worker.pid); | |
| // Create router | |
| const router = await worker.createRouter({ | |
| mediaCodecs: [ | |
| { | |
| kind: "audio", | |
| mimeType: "audio/opus", | |
| clockRate: 48000, | |
| channels: 2, | |
| }, | |
| { | |
| kind: "video", | |
| mimeType: "video/VP8", | |
| clockRate: 90000, | |
| parameters: {}, | |
| }, | |
| { | |
| kind: "video", | |
| mimeType: "video/H264", | |
| clockRate: 90000, | |
| parameters: { | |
| "packetization-mode": 1, | |
| "profile-level-id": "42e01f", | |
| "level-asymmetry-allowed": 1, | |
| }, | |
| }, | |
| ], | |
| }); | |
| console.log("β mediasoup router created"); | |
| const transports = new Map(); | |
| const producers = new Map(); | |
| const consumers = new Map(); | |
| // Middleware for logging requests | |
| app.use((req, res, next) => { | |
| console.log(`π¨ ${req.method} ${req.path} - ${new Date().toISOString()}`); | |
| next(); | |
| }); | |
| // Serve publisher HTML | |
| 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>WHIP 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; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| } | |
| .controls { | |
| display: flex; | |
| gap: 10px; | |
| margin: 20px 0; | |
| flex-wrap: wrap; | |
| } | |
| button { | |
| background: #f5576c; | |
| color: white; | |
| border: none; | |
| padding: 12px 30px; | |
| border-radius: 8px; | |
| font-size: 16px; | |
| font-weight: 600; | |
| cursor: pointer; | |
| transition: all 0.3s; | |
| flex: 1; | |
| min-width: 150px; | |
| } | |
| button:hover { background: #e04556; transform: translateY(-2px); } | |
| button:active { transform: translateY(0); } | |
| button:disabled { | |
| background: #ccc; | |
| cursor: not-allowed; | |
| transform: none; | |
| } | |
| button.secondary { | |
| background: #6c757d; | |
| } | |
| button.secondary:hover { | |
| background: #5a6268; | |
| } | |
| .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; | |
| min-width: 200px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>πΉ WHIP 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 Streaming</button> | |
| <button id="stopBtn" onclick="stopStream()" disabled class="secondary">βΉ Stop</button> | |
| </div> | |
| <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-top: 20px; font-size: 14px; color: #666;"> | |
| <strong>Instructions:</strong><br> | |
| 1. Select Camera or Screen Share<br> | |
| 2. Click "Start Streaming"<br> | |
| 3. View at: <a href="/" target="_blank">Viewer Page</a> | |
| </div> | |
| </div> | |
| <script> | |
| let stream = null; | |
| let pc = null; | |
| const WHIP_ENDPOINT = window.location.origin + '/whip'; | |
| const status = document.getElementById('status'); | |
| const startBtn = document.getElementById('startBtn'); | |
| const stopBtn = document.getElementById('stopBtn'); | |
| function updateStatus(msg, type = 'idle') { | |
| status.className = 'status ' + type; | |
| status.textContent = msg; | |
| } | |
| async function startStream() { | |
| try { | |
| updateStatus('Getting media...', 'idle'); | |
| startBtn.disabled = true; | |
| const sourceType = document.getElementById('sourceType').value; | |
| // Get media stream | |
| if (sourceType === 'camera') { | |
| stream = await navigator.mediaDevices.getUserMedia({ | |
| video: { width: 1280, height: 720 }, | |
| audio: true | |
| }); | |
| } else { | |
| stream = await navigator.mediaDevices.getDisplayMedia({ | |
| video: { width: 1920, height: 1080 }, | |
| audio: true | |
| }); | |
| } | |
| document.getElementById('preview').srcObject = stream; | |
| updateStatus('Connecting to server...', 'idle'); | |
| // Create peer connection | |
| pc = new RTCPeerConnection({ | |
| iceServers: [ | |
| { urls: 'stun:stun.l.google.com:19302' }, | |
| { urls: 'stun:stun1.l.google.com:19302' } | |
| ] | |
| }); | |
| // Add tracks | |
| stream.getTracks().forEach(track => { | |
| console.log('Adding track:', track.kind); | |
| pc.addTrack(track, stream); | |
| }); | |
| // Monitor connection | |
| pc.oniceconnectionstatechange = () => { | |
| console.log('ICE connection state:', pc.iceConnectionState); | |
| if (pc.iceConnectionState === 'failed' || pc.iceConnectionState === 'disconnected') { | |
| updateStatus('β Connection lost', 'error'); | |
| } | |
| }; | |
| // Create offer | |
| const offer = await pc.createOffer(); | |
| await pc.setLocalDescription(offer); | |
| // Wait for ICE gathering | |
| updateStatus('Gathering connection info...', 'idle'); | |
| await new Promise(resolve => { | |
| if (pc.iceGatheringState === 'complete') { | |
| resolve(); | |
| } else { | |
| const checkState = () => { | |
| if (pc.iceGatheringState === 'complete') { | |
| pc.removeEventListener('icegatheringstatechange', checkState); | |
| resolve(); | |
| } | |
| }; | |
| pc.addEventListener('icegatheringstatechange', checkState); | |
| } | |
| }); | |
| console.log('Sending offer to WHIP endpoint...'); | |
| // Send to WHIP endpoint | |
| const response = await fetch(WHIP_ENDPOINT, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/sdp' | |
| }, | |
| body: pc.localDescription.sdp | |
| }); | |
| if (!response.ok) { | |
| const errorText = await response.text(); | |
| throw new Error('WHIP failed: ' + response.status + ' - ' + errorText); | |
| } | |
| const answerSdp = await response.text(); | |
| console.log('Received answer from server'); | |
| await pc.setRemoteDescription({ | |
| type: 'answer', | |
| sdp: answerSdp | |
| }); | |
| updateStatus('π΄ STREAMING LIVE', 'streaming'); | |
| stopBtn.disabled = false; | |
| console.log('β Streaming started successfully'); | |
| } catch (error) { | |
| console.error('Error:', error); | |
| updateStatus('β Error: ' + error.message, 'error'); | |
| startBtn.disabled = false; | |
| if (stream) { | |
| stream.getTracks().forEach(t => t.stop()); | |
| } | |
| } | |
| } | |
| function stopStream() { | |
| if (pc) { | |
| pc.close(); | |
| pc = null; | |
| } | |
| if (stream) { | |
| stream.getTracks().forEach(t => t.stop()); | |
| stream = null; | |
| } | |
| document.getElementById('preview').srcObject = null; | |
| updateStatus('Stream stopped', 'idle'); | |
| startBtn.disabled = false; | |
| stopBtn.disabled = true; | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| `); | |
| }); | |
| // Serve viewer HTML on root route | |
| 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>WHEP 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; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .status.waiting { background: #fff3cd; color: #856404; } | |
| .status.connecting { background: #d1ecf1; color: #0c5460; } | |
| .status.live { background: #d4edda; color: #155724; } | |
| .status.error { background: #f8d7da; color: #721c24; } | |
| .dot { | |
| width: 10px; | |
| height: 10px; | |
| border-radius: 50%; | |
| display: inline-block; | |
| } | |
| .dot.pulse { | |
| animation: pulse 2s infinite; | |
| } | |
| @keyframes pulse { | |
| 0%, 100% { opacity: 1; } | |
| 50% { opacity: 0.5; } | |
| } | |
| video { | |
| width: 100%; | |
| border-radius: 12px; | |
| background: #000; | |
| margin: 20px 0; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| } | |
| button { | |
| background: #667eea; | |
| color: white; | |
| border: none; | |
| padding: 12px 30px; | |
| border-radius: 8px; | |
| font-size: 16px; | |
| font-weight: 600; | |
| cursor: pointer; | |
| transition: all 0.3s; | |
| } | |
| button:hover { background: #5568d3; transform: translateY(-2px); } | |
| button:active { transform: translateY(0); } | |
| button:disabled { | |
| background: #ccc; | |
| cursor: not-allowed; | |
| transform: none; | |
| } | |
| .info { | |
| background: #f8f9fa; | |
| padding: 15px; | |
| border-radius: 8px; | |
| margin-top: 20px; | |
| font-size: 14px; | |
| color: #666; | |
| } | |
| .info strong { color: #333; } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>π‘ WHEP Stream Viewer</h1> | |
| <div id="status" class="status waiting"> | |
| <span class="dot pulse" style="background: #856404;"></span> | |
| Waiting for stream... | |
| </div> | |
| <video id="video" autoplay playsinline controls></video> | |
| <button id="playBtn" onclick="startViewing()">βΆοΈ Start Viewing</button> | |
| <div class="info"> | |
| <strong>Instructions:</strong><br> | |
| 1. Start streaming at: <a href="/publish" target="_blank">Publisher Page</a><br> | |
| 2. Click "Start Viewing" to watch the stream<br> | |
| 3. Stream will auto-connect when available | |
| </div> | |
| </div> | |
| <script> | |
| const video = document.getElementById('video'); | |
| const status = document.getElementById('status'); | |
| const playBtn = document.getElementById('playBtn'); | |
| const WHEP_ENDPOINT = window.location.origin + '/whep'; | |
| let pc = null; | |
| function updateStatus(msg, type = 'waiting') { | |
| const colors = { | |
| waiting: '#856404', | |
| connecting: '#0c5460', | |
| live: '#155724', | |
| error: '#721c24' | |
| }; | |
| status.className = 'status ' + type; | |
| status.innerHTML = \`<span class="dot pulse" style="background: \${colors[type]};"></span>\${msg}\`; | |
| } | |
| async function startViewing() { | |
| try { | |
| updateStatus('Connecting to stream...', 'connecting'); | |
| playBtn.disabled = true; | |
| // Create peer connection | |
| pc = new RTCPeerConnection({ | |
| iceServers: [ | |
| { urls: 'stun:stun.l.google.com:19302' }, | |
| { urls: 'stun:stun1.l.google.com:19302' } | |
| ] | |
| }); | |
| // Handle incoming tracks | |
| pc.ontrack = (event) => { | |
| console.log('πΉ Received track:', event.track.kind); | |
| if (!video.srcObject) { | |
| video.srcObject = event.streams[0]; | |
| } | |
| updateStatus('π΄ LIVE', 'live'); | |
| playBtn.style.display = 'none'; | |
| }; | |
| // Handle connection state | |
| pc.onconnectionstatechange = () => { | |
| console.log('Connection state:', pc.connectionState); | |
| if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') { | |
| updateStatus('β Connection lost', 'error'); | |
| playBtn.disabled = false; | |
| playBtn.style.display = 'block'; | |
| } | |
| }; | |
| // Add transceivers | |
| pc.addTransceiver('video', { direction: 'recvonly' }); | |
| pc.addTransceiver('audio', { direction: 'recvonly' }); | |
| // Create offer | |
| const offer = await pc.createOffer(); | |
| await pc.setLocalDescription(offer); | |
| // Wait for ICE gathering | |
| await new Promise(resolve => { | |
| if (pc.iceGatheringState === 'complete') { | |
| resolve(); | |
| } else { | |
| const checkState = () => { | |
| if (pc.iceGatheringState === 'complete') { | |
| pc.removeEventListener('icegatheringstatechange', checkState); | |
| resolve(); | |
| } | |
| }; | |
| pc.addEventListener('icegatheringstatechange', checkState); | |
| } | |
| }); | |
| // Send WHEP request | |
| const response = await fetch(WHEP_ENDPOINT, { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/sdp' }, | |
| body: pc.localDescription.sdp | |
| }); | |
| if (!response.ok) { | |
| throw new Error('No stream available. Start streaming first!'); | |
| } | |
| const answerSdp = await response.text(); | |
| await pc.setRemoteDescription({ type: 'answer', sdp: answerSdp }); | |
| console.log('β WHEP connection established'); | |
| } catch (error) { | |
| console.error('Error:', error); | |
| updateStatus('β ' + error.message, 'error'); | |
| playBtn.disabled = false; | |
| } | |
| } | |
| // Auto-check for stream every 3 seconds | |
| setInterval(async () => { | |
| if (!pc || pc.connectionState === 'failed') { | |
| try { | |
| const response = await fetch('/status'); | |
| const data = await response.json(); | |
| if (data.hasStream && status.className.includes('waiting')) { | |
| updateStatus('Stream available! Click to watch', 'waiting'); | |
| } | |
| } catch (e) {} | |
| } | |
| }, 3000); | |
| </script> | |
| </body> | |
| </html> | |
| `); | |
| }); | |
| // WHIP endpoint - for publishing | |
| app.post("/whip", async (req, res) => { | |
| try { | |
| console.log("π₯ WHIP publish request received"); | |
| // Create transport for producer | |
| const transport = await router.createWebRtcTransport({ | |
| listenIps: [{ | |
| ip: "0.0.0.0", | |
| announcedIp: ANNOUNCED_IP | |
| }], | |
| enableUdp: true, | |
| enableTcp: true, | |
| preferUdp: true, | |
| }); | |
| const transportId = transport.id; | |
| transports.set(transportId, transport); | |
| console.log("β Producer transport created:", transportId); | |
| // Parse SDP offer | |
| const offerSdp = req.body; | |
| // Generate answer SDP | |
| const answerSdp = createAnswerSdp(transport, offerSdp); | |
| // Set up transport listeners | |
| transport.on("dtlsstatechange", async (dtlsState) => { | |
| console.log("π DTLS state:", dtlsState); | |
| if (dtlsState === "connected") { | |
| console.log("β DTLS connected, ready to produce"); | |
| } | |
| }); | |
| // Store for later producer creation | |
| transport.appData = { offerSdp }; | |
| res.setHeader("Content-Type", "application/sdp"); | |
| res.setHeader("Location", `/whip/${transportId}`); | |
| res.status(201).send(answerSdp); | |
| console.log("β WHIP answer sent"); | |
| } catch (error) { | |
| console.error("β WHIP error:", error); | |
| res.status(500).json({ error: error.message }); | |
| } | |
| }); | |
| // WHEP endpoint - for viewing | |
| app.post("/whep", async (req, res) => { | |
| try { | |
| console.log("ποΈ WHEP view request received"); | |
| // Check if we have any producers | |
| const hasProducers = producers.size > 0; | |
| if (!hasProducers) { | |
| console.log("β οΈ No active stream"); | |
| return res.status(404).send("No stream available"); | |
| } | |
| // Create transport for consumer | |
| const transport = await router.createWebRtcTransport({ | |
| listenIps: [{ | |
| ip: "0.0.0.0", | |
| announcedIp: ANNOUNCED_IP | |
| }], | |
| enableUdp: true, | |
| enableTcp: true, | |
| preferUdp: true, | |
| }); | |
| const transportId = transport.id; | |
| transports.set(transportId, transport); | |
| console.log("β Consumer transport created:", transportId); | |
| const offerSdp = req.body; | |
| // Generate answer SDP | |
| const answerSdp = createAnswerSdp(transport, offerSdp); | |
| transport.on("dtlsstatechange", (dtlsState) => { | |
| console.log("π Consumer DTLS state:", dtlsState); | |
| }); | |
| res.setHeader("Content-Type", "application/sdp"); | |
| res.setHeader("Location", `/whep/${transportId}`); | |
| res.status(201).send(answerSdp); | |
| console.log("β WHEP answer sent"); | |
| } catch (error) { | |
| console.error("β WHEP error:", error); | |
| res.status(500).json({ error: error.message }); | |
| } | |
| }); | |
| // Status endpoint | |
| app.get("/status", (req, res) => { | |
| res.json({ | |
| hasStream: producers.size > 0, | |
| workerPid: worker.pid, | |
| producers: producers.size, | |
| consumers: consumers.size, | |
| transports: transports.size, | |
| }); | |
| }); | |
| // Helper function to create SDP answer | |
| function createAnswerSdp(transport, offerSdp) { | |
| const ice = transport.iceParameters; | |
| const dtls = transport.dtlsParameters; | |
| const iceCandidates = transport.iceCandidates; | |
| let sdp = `v=0 | |
| o=- 0 0 IN IP4 0.0.0.0 | |
| s=- | |
| t=0 0 | |
| a=group:BUNDLE 0 | |
| a=msid-semantic: WMS * | |
| `; | |
| // Add media section | |
| sdp += `m=video 9 UDP/TLS/RTP/SAVPF 96 | |
| c=IN IP4 0.0.0.0 | |
| a=rtcp:9 IN IP4 0.0.0.0 | |
| a=ice-ufrag:${ice.usernameFragment} | |
| a=ice-pwd:${ice.password} | |
| a=ice-options:trickle | |
| a=fingerprint:${dtls.fingerprints[0].algorithm} ${dtls.fingerprints[0].value} | |
| a=setup:active | |
| a=mid:0 | |
| a=sendrecv | |
| a=rtcp-mux | |
| a=rtcp-rsize | |
| a=rtpmap:96 VP8/90000 | |
| `; | |
| // Add ICE candidates | |
| iceCandidates.forEach(candidate => { | |
| sdp += `a=candidate:${candidate.foundation} ${candidate.component} ${candidate.protocol} ${candidate.priority} ${candidate.ip} ${candidate.port} typ ${candidate.type} | |
| `; | |
| }); | |
| sdp += `a=end-of-candidates | |
| `; | |
| return sdp; | |
| } | |
| // Start server | |
| const PORT = process.env.PORT || 7860; | |
| http.createServer(app).listen(PORT, () => { | |
| console.log(`\n${"=".repeat(50)}`); | |
| console.log(`π WHIP/WHEP Server running on port ${PORT}`); | |
| console.log(`${"=".repeat(50)}`); | |
| console.log(`πΊ Viewer: http://localhost:${PORT}/`); | |
| console.log(`πΉ Publisher: http://localhost:${PORT}/publish`); | |
| console.log(`π€ WHIP: http://localhost:${PORT}/whip`); | |
| console.log(`π₯ WHEP: http://localhost:${PORT}/whep`); | |
| console.log(`${"=".repeat(50)}\n`); | |
| }); |