veltrixcode commited on
Commit
1122a33
Β·
verified Β·
1 Parent(s): a1df4b6

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +425 -33
server.js CHANGED
@@ -5,50 +5,442 @@ import mediasoup from "mediasoup";
5
  const app = express();
6
  app.use(express.json());
7
 
8
- const worker = await mediasoup.createWorker();
 
 
 
 
 
 
 
 
 
 
 
9
  const router = await worker.createRouter({
10
- mediaCodecs: [{
11
- kind: "video",
12
- mimeType: "video/H264",
13
- clockRate: 90000,
14
- parameters: { "packetization-mode": 1, "profile-level-id": "42e01f" }
15
- }]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  });
17
 
18
- let producer;
19
 
20
- app.post("/whip", async (req, res) => {
21
- const transport = await router.createWebRtcTransport({
22
- listenIps: [{ ip: "0.0.0.0", announcedIp: null }],
23
- enableUdp: true, enableTcp: true, preferUdp: true
24
- });
25
 
26
- const sdp = req.body.sdp;
 
 
 
 
27
 
28
- await transport.connect({ dtlsParameters: sdp.dtlsParameters });
29
- producer = await transport.produce({
30
- kind: "video",
31
- rtpParameters: sdp.rtpParameters
32
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- res.json({ ok: true });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  });
36
 
37
- app.get("/whep", async (req, res) => {
38
- if (!producer) return res.status(404).send("No stream");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- const transport = await router.createWebRtcTransport({
41
- listenIps: [{ ip: "0.0.0.0", announcedIp: null }],
42
- enableUdp: true, enableTcp: true, preferUdp: true
43
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- const consumer = await transport.consume({
46
- producerId: producer.id,
47
- rtpCapabilities: router.rtpCapabilities,
48
- paused: false
 
49
  });
50
-
51
- res.json({ consumer });
52
  });
53
 
54
- http.createServer(app).listen(7860);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  const app = express();
6
  app.use(express.json());
7
 
8
+ console.log("πŸš€ Starting mediasoup WHIP/WHEP server...");
9
+
10
+ // Create mediasoup worker
11
+ const worker = await mediasoup.createWorker({
12
+ logLevel: "warn",
13
+ rtcMinPort: 10000,
14
+ rtcMaxPort: 10100,
15
+ });
16
+
17
+ console.log("βœ… mediasoup worker created [pid:%d]", worker.pid);
18
+
19
+ // Create router
20
  const router = await worker.createRouter({
21
+ mediaCodecs: [
22
+ {
23
+ kind: "audio",
24
+ mimeType: "audio/opus",
25
+ clockRate: 48000,
26
+ channels: 2,
27
+ },
28
+ {
29
+ kind: "video",
30
+ mimeType: "video/VP8",
31
+ clockRate: 90000,
32
+ parameters: {},
33
+ },
34
+ {
35
+ kind: "video",
36
+ mimeType: "video/H264",
37
+ clockRate: 90000,
38
+ parameters: {
39
+ "packetization-mode": 1,
40
+ "profile-level-id": "42e01f",
41
+ "level-asymmetry-allowed": 1,
42
+ },
43
+ },
44
+ ],
45
  });
46
 
47
+ console.log("βœ… mediasoup router created");
48
 
49
+ let producerTransport = null;
50
+ let producer = null;
 
 
 
51
 
52
+ // Middleware for logging requests
53
+ app.use((req, res, next) => {
54
+ console.log(`πŸ“¨ ${req.method} ${req.path} - ${new Date().toISOString()}`);
55
+ next();
56
+ });
57
 
58
+ // Serve viewer HTML on root route
59
+ app.get("/", (req, res) => {
60
+ res.send(`
61
+ <!DOCTYPE html>
62
+ <html lang="en">
63
+ <head>
64
+ <meta charset="UTF-8">
65
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
66
+ <title>WHEP Stream Viewer</title>
67
+ <style>
68
+ * { margin: 0; padding: 0; box-sizing: border-box; }
69
+ body {
70
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
71
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
72
+ min-height: 100vh;
73
+ display: flex;
74
+ align-items: center;
75
+ justify-content: center;
76
+ padding: 20px;
77
+ }
78
+ .container {
79
+ background: white;
80
+ border-radius: 20px;
81
+ box-shadow: 0 20px 60px rgba(0,0,0,0.3);
82
+ padding: 40px;
83
+ max-width: 900px;
84
+ width: 100%;
85
+ }
86
+ h1 {
87
+ color: #333;
88
+ margin-bottom: 10px;
89
+ font-size: 2em;
90
+ }
91
+ .status {
92
+ padding: 12px 20px;
93
+ border-radius: 8px;
94
+ margin: 20px 0;
95
+ font-weight: 600;
96
+ display: flex;
97
+ align-items: center;
98
+ gap: 10px;
99
+ }
100
+ .status.waiting { background: #fff3cd; color: #856404; }
101
+ .status.connecting { background: #d1ecf1; color: #0c5460; }
102
+ .status.live { background: #d4edda; color: #155724; }
103
+ .status.error { background: #f8d7da; color: #721c24; }
104
+ .dot {
105
+ width: 10px;
106
+ height: 10px;
107
+ border-radius: 50%;
108
+ display: inline-block;
109
+ }
110
+ .dot.pulse {
111
+ animation: pulse 2s infinite;
112
+ }
113
+ @keyframes pulse {
114
+ 0%, 100% { opacity: 1; }
115
+ 50% { opacity: 0.5; }
116
+ }
117
+ video {
118
+ width: 100%;
119
+ border-radius: 12px;
120
+ background: #000;
121
+ margin: 20px 0;
122
+ box-shadow: 0 10px 30px rgba(0,0,0,0.2);
123
+ }
124
+ button {
125
+ background: #667eea;
126
+ color: white;
127
+ border: none;
128
+ padding: 12px 30px;
129
+ border-radius: 8px;
130
+ font-size: 16px;
131
+ font-weight: 600;
132
+ cursor: pointer;
133
+ transition: all 0.3s;
134
+ }
135
+ button:hover { background: #5568d3; transform: translateY(-2px); }
136
+ button:active { transform: translateY(0); }
137
+ button:disabled {
138
+ background: #ccc;
139
+ cursor: not-allowed;
140
+ transform: none;
141
+ }
142
+ .info {
143
+ background: #f8f9fa;
144
+ padding: 15px;
145
+ border-radius: 8px;
146
+ margin-top: 20px;
147
+ font-size: 14px;
148
+ color: #666;
149
+ }
150
+ .info strong { color: #333; }
151
+ </style>
152
+ </head>
153
+ <body>
154
+ <div class="container">
155
+ <h1>πŸ“‘ WHEP Stream Viewer</h1>
156
+ <div id="status" class="status waiting">
157
+ <span class="dot pulse" style="background: #856404;"></span>
158
+ Waiting for stream...
159
+ </div>
160
+
161
+ <video id="video" autoplay playsinline controls></video>
162
+
163
+ <button id="playBtn" onclick="startViewing()">▢️ Start Viewing</button>
164
+
165
+ <div class="info">
166
+ <strong>Instructions:</strong><br>
167
+ 1. Start streaming to this server using WHIP<br>
168
+ 2. Click "Start Viewing" to watch the stream<br>
169
+ 3. Server endpoint: <code>http://localhost:7860</code>
170
+ </div>
171
+ </div>
172
 
173
+ <script>
174
+ const video = document.getElementById('video');
175
+ const status = document.getElementById('status');
176
+ const playBtn = document.getElementById('playBtn');
177
+
178
+ let pc = null;
179
+
180
+ function updateStatus(msg, type = 'waiting') {
181
+ const colors = {
182
+ waiting: '#856404',
183
+ connecting: '#0c5460',
184
+ live: '#155724',
185
+ error: '#721c24'
186
+ };
187
+ status.className = 'status ' + type;
188
+ status.innerHTML = \`<span class="dot pulse" style="background: \${colors[type]};"></span>\${msg}\`;
189
+ }
190
+
191
+ async function startViewing() {
192
+ try {
193
+ updateStatus('Connecting to stream...', 'connecting');
194
+ playBtn.disabled = true;
195
+
196
+ // Create peer connection
197
+ pc = new RTCPeerConnection({
198
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
199
+ });
200
+
201
+ // Handle incoming tracks
202
+ pc.ontrack = (event) => {
203
+ console.log('πŸ“Ή Received track:', event.track.kind);
204
+ video.srcObject = event.streams[0];
205
+ updateStatus('πŸ”΄ LIVE', 'live');
206
+ playBtn.style.display = 'none';
207
+ };
208
+
209
+ // Handle connection state
210
+ pc.onconnectionstatechange = () => {
211
+ console.log('Connection state:', pc.connectionState);
212
+ if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
213
+ updateStatus('❌ Connection lost', 'error');
214
+ playBtn.disabled = false;
215
+ playBtn.style.display = 'block';
216
+ }
217
+ };
218
+
219
+ // Add transceiver for receiving video
220
+ pc.addTransceiver('video', { direction: 'recvonly' });
221
+ pc.addTransceiver('audio', { direction: 'recvonly' });
222
+
223
+ // Create offer
224
+ const offer = await pc.createOffer();
225
+ await pc.setLocalDescription(offer);
226
+
227
+ // Wait for ICE gathering
228
+ await new Promise(resolve => {
229
+ if (pc.iceGatheringState === 'complete') {
230
+ resolve();
231
+ } else {
232
+ pc.onicegatheringstatechange = () => {
233
+ if (pc.iceGatheringState === 'complete') resolve();
234
+ };
235
+ }
236
+ });
237
+
238
+ // Send WHEP request
239
+ const response = await fetch('/whep', {
240
+ method: 'POST',
241
+ headers: { 'Content-Type': 'application/sdp' },
242
+ body: pc.localDescription.sdp
243
+ });
244
+
245
+ if (!response.ok) {
246
+ throw new Error('No stream available. Start streaming first!');
247
+ }
248
+
249
+ const answerSdp = await response.text();
250
+ await pc.setRemoteDescription({ type: 'answer', sdp: answerSdp });
251
+
252
+ console.log('βœ… WHEP connection established');
253
+
254
+ } catch (error) {
255
+ console.error('Error:', error);
256
+ updateStatus('❌ ' + error.message, 'error');
257
+ playBtn.disabled = false;
258
+ }
259
+ }
260
+
261
+ // Auto-check for stream every 3 seconds
262
+ setInterval(async () => {
263
+ if (!pc || pc.connectionState === 'failed') {
264
+ try {
265
+ const response = await fetch('/status');
266
+ const data = await response.json();
267
+ if (data.hasStream && status.className.includes('waiting')) {
268
+ updateStatus('Stream available! Click to watch', 'waiting');
269
+ }
270
+ } catch (e) {}
271
+ }
272
+ }, 3000);
273
+ </script>
274
+ </body>
275
+ </html>
276
+ `);
277
  });
278
 
279
+ // WHIP endpoint - for publishing
280
+ app.post("/whip", async (req, res) => {
281
+ try {
282
+ console.log("πŸŽ₯ WHIP publish request received");
283
+
284
+ const offerSdp = req.body;
285
+ console.log("πŸ“ Received SDP offer");
286
+
287
+ // Create transport for producer
288
+ producerTransport = await router.createWebRtcTransport({
289
+ listenIps: [{ ip: "0.0.0.0", announcedIp: "127.0.0.1" }],
290
+ enableUdp: true,
291
+ enableTcp: true,
292
+ preferUdp: true,
293
+ });
294
+
295
+ console.log("βœ… Producer transport created");
296
+
297
+ // Get transport parameters for answer
298
+ const answer = {
299
+ type: "answer",
300
+ sdp: generateAnswerSdp(producerTransport, offerSdp),
301
+ };
302
+
303
+ // Set up transport listeners
304
+ producerTransport.on("dtlsstatechange", (dtlsState) => {
305
+ console.log("πŸ” DTLS state:", dtlsState);
306
+ if (dtlsState === "closed") {
307
+ producerTransport.close();
308
+ }
309
+ });
310
+
311
+ res.setHeader("Content-Type", "application/sdp");
312
+ res.setHeader("Location", "/whip/stream");
313
+ res.status(201).send(answer.sdp);
314
+
315
+ console.log("βœ… WHIP answer sent");
316
+
317
+ } catch (error) {
318
+ console.error("❌ WHIP error:", error);
319
+ res.status(500).json({ error: error.message });
320
+ }
321
+ });
322
 
323
+ // WHEP endpoint - for viewing
324
+ app.post("/whep", async (req, res) => {
325
+ try {
326
+ console.log("πŸ‘οΈ WHEP view request received");
327
+
328
+ if (!producer) {
329
+ console.log("⚠️ No active stream");
330
+ return res.status(404).send("No stream available");
331
+ }
332
+
333
+ const offerSdp = req.body;
334
+ console.log("πŸ“ Received WHEP SDP offer");
335
+
336
+ // Create transport for consumer
337
+ const consumerTransport = await router.createWebRtcTransport({
338
+ listenIps: [{ ip: "0.0.0.0", announcedIp: "127.0.0.1" }],
339
+ enableUdp: true,
340
+ enableTcp: true,
341
+ preferUdp: true,
342
+ });
343
+
344
+ console.log("βœ… Consumer transport created");
345
+
346
+ // Create consumer
347
+ const consumer = await consumerTransport.consume({
348
+ producerId: producer.id,
349
+ rtpCapabilities: router.rtpCapabilities,
350
+ paused: false,
351
+ });
352
+
353
+ console.log("βœ… Consumer created for producer:", producer.id);
354
+
355
+ const answer = {
356
+ type: "answer",
357
+ sdp: generateAnswerSdp(consumerTransport, offerSdp, consumer),
358
+ };
359
+
360
+ consumerTransport.on("dtlsstatechange", (dtlsState) => {
361
+ console.log("πŸ” Consumer DTLS state:", dtlsState);
362
+ if (dtlsState === "closed") {
363
+ consumerTransport.close();
364
+ }
365
+ });
366
+
367
+ res.setHeader("Content-Type", "application/sdp");
368
+ res.setHeader("Location", "/whep/stream");
369
+ res.status(201).send(answer.sdp);
370
+
371
+ console.log("βœ… WHEP answer sent");
372
+
373
+ } catch (error) {
374
+ console.error("❌ WHEP error:", error);
375
+ res.status(500).json({ error: error.message });
376
+ }
377
+ });
378
 
379
+ // Status endpoint
380
+ app.get("/status", (req, res) => {
381
+ res.json({
382
+ hasStream: !!producer,
383
+ workerPid: worker.pid,
384
  });
 
 
385
  });
386
 
387
+ // Helper function to generate SDP answer
388
+ function generateAnswerSdp(transport, offerSdp, consumer = null) {
389
+ const ice = transport.iceParameters;
390
+ const dtls = transport.dtlsParameters;
391
+
392
+ let sdp = `v=0
393
+ o=- 0 0 IN IP4 127.0.0.1
394
+ s=-
395
+ t=0 0
396
+ a=group:BUNDLE 0
397
+ a=msid-semantic: WMS *
398
+ `;
399
+
400
+ if (consumer) {
401
+ sdp += `m=video 9 UDP/TLS/RTP/SAVPF 96
402
+ c=IN IP4 0.0.0.0
403
+ a=rtcp:9 IN IP4 0.0.0.0
404
+ a=ice-ufrag:${ice.usernameFragment}
405
+ a=ice-pwd:${ice.password}
406
+ a=ice-options:trickle
407
+ a=fingerprint:${dtls.fingerprints[0].algorithm} ${dtls.fingerprints[0].value}
408
+ a=setup:active
409
+ a=mid:0
410
+ a=recvonly
411
+ a=rtcp-mux
412
+ a=rtcp-rsize
413
+ a=rtpmap:96 VP8/90000
414
+ a=ssrc:${consumer.rtpParameters.encodings[0].ssrc} cname:mediasoup
415
+ `;
416
+ } else {
417
+ sdp += `m=video 9 UDP/TLS/RTP/SAVPF 96
418
+ c=IN IP4 0.0.0.0
419
+ a=rtcp:9 IN IP4 0.0.0.0
420
+ a=ice-ufrag:${ice.usernameFragment}
421
+ a=ice-pwd:${ice.password}
422
+ a=ice-options:trickle
423
+ a=fingerprint:${dtls.fingerprints[0].algorithm} ${dtls.fingerprints[0].value}
424
+ a=setup:passive
425
+ a=mid:0
426
+ a=sendrecv
427
+ a=rtcp-mux
428
+ a=rtcp-rsize
429
+ a=rtpmap:96 VP8/90000
430
+ `;
431
+ }
432
+
433
+ return sdp;
434
+ }
435
+
436
+ // Start server
437
+ const PORT = 7860;
438
+ http.createServer(app).listen(PORT, () => {
439
+ console.log(`\n${"=".repeat(50)}`);
440
+ console.log(`πŸŽ‰ WHIP/WHEP Server running on port ${PORT}`);
441
+ console.log(`${"=".repeat(50)}`);
442
+ console.log(`πŸ“Ί Viewer: http://localhost:${PORT}/`);
443
+ console.log(`πŸ“€ WHIP: http://localhost:${PORT}/whip`);
444
+ console.log(`πŸ“₯ WHEP: http://localhost:${PORT}/whep`);
445
+ console.log(`${"=".repeat(50)}\n`);
446
+ });