-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
586 lines (497 loc) · 19.1 KB
/
Copy pathserver.js
File metadata and controls
586 lines (497 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
const express = require('express');
const http = require('http');
const https = require('https');
const fs = require('fs');
const { Server } = require('socket.io');
const Bonjour = require('bonjour-service');
const QRCode = require('qrcode');
const path = require('path');
const os = require('os');
const config = require('./config.json');
// Custom logger support for GUI integration
let customLogger = null;
function log(message) {
console.log(message);
if (customLogger) customLogger(message);
}
const app = express();
// Try to create HTTPS server with self-signed certificates
let httpsServer;
let useHttps = false;
try {
const httpsOptions = {
key: fs.readFileSync(path.join(__dirname, 'localhost-key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'localhost-cert.pem'))
};
httpsServer = https.createServer(httpsOptions, app);
useHttps = true;
log('✅ HTTPS certificates found - iOS/Safari support enabled');
} catch (error) {
log('⚠️ HTTPS certificates not found - using HTTP only');
log(' iOS/Safari will not work over network. Run: npm run generate-cert');
}
// Always create HTTP server for local access
const httpServer = http.createServer(app);
// Create Socket.IO instance that works on both servers
let io;
if (useHttps) {
// Attach Socket.IO to both HTTP and HTTPS servers
io = new Server({
cors: {
origin: '*',
methods: ['GET', 'POST']
},
perMessageDeflate: false, // Disable compression for LAN
httpCompression: false,
transports: ['websocket', 'polling'], // Prefer websocket
pingTimeout: 60000,
pingInterval: 25000
});
io.attach(httpsServer);
io.attach(httpServer);
} else {
// HTTP only mode
io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST']
},
perMessageDeflate: false, // Disable compression
httpCompression: false
});
}
// Middleware
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Serve specific pages for clean URLs
app.get('/desktop', (req, res) => {
res.sendFile(path.join(__dirname, 'public/desktop/index.html'));
});
app.get('/mobile', (req, res) => {
res.sendFile(path.join(__dirname, 'public/mobile/index.html'));
});
app.get('/viewer', (req, res) => {
res.sendFile(path.join(__dirname, 'public/viewer/index.html'));
});
// Store active streams and connections
const streams = new Map();
const rooms = new Map();
// Initialize bandwidth manager
const BandwidthManager = require('./bandwidth-manager');
const bandwidthManager = new BandwidthManager();
// Helper to get local IP address
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return '127.0.0.1';
}
// ✅ Broadcast total network usage
function broadcastNetworkUsage() {
let totalBitrate = 0;
activeStreams.forEach(bitrate => totalBitrate += bitrate);
// Broadcast total bps and stream count
io.emit('network-usage', {
totalBitrate: totalBitrate,
streamCount: activeStreams.size
});
}
const localIP = getLocalIP();
const httpPort = config.server.port;
const httpsPort = config.server.httpsPort || 3443;
const httpURL = `http://${localIP}:${httpPort}`;
const httpsURL = `https://${localIP}:${httpsPort}`;
const serverURL = useHttps ? httpsURL : httpURL;
// Initial setup logs moved to startServer() function
// Bonjour/mDNS service for auto-discovery (initialized in startServer)
let bonjourService = null;
// REST API Endpoints
// Health check
app.get('/health', (req, res) => {
res.json({
status: 'ok',
streams: streams.size,
uptime: process.uptime()
});
});
// Get configuration
app.get('/api/config', (req, res) => {
res.json({
webrtc: config.webrtc,
video: config.video,
serverURL
});
});
// Get active streams
app.get('/api/streams', (req, res) => {
const streamList = Array.from(streams.values()).map(stream => ({
id: stream.id,
name: stream.name,
status: stream.status,
viewers: stream.viewers,
createdAt: stream.createdAt,
stats: stream.stats
}));
res.json(streamList);
});
// Generate QR code for mobile access
app.get('/api/qr/mobile', async (req, res) => {
try {
const url = `${serverURL}/mobile`;
const qr = await QRCode.toDataURL(url, {
width: 300,
margin: 2,
color: {
dark: '#000000',
light: '#ffffff'
}
});
res.json({ qr, url });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// WebRTC Signaling via Socket.IO
const activeStreams = new Map(); // Store stream info: { id, bitrate }
io.on('connection', (socket) => {
log(`✅ Client connected: ${socket.id}`);
// Register as streamer
socket.on('register-streamer', (data) => {
const streamId = data.streamId || `stream-${Date.now()}`;
const quality = data.quality || '1080p30';
// Check if new streamer can be accepted based on available bandwidth
const acceptance = bandwidthManager.canAcceptNewStreamer(quality, streamId);
if (!acceptance.allowed) {
log(`❌ Streamer rejected: insufficient bandwidth for ${quality}`);
socket.emit('bandwidth-insufficient', {
required: acceptance.required,
available: acceptance.available,
message: acceptance.message
});
return; // REJECT connection
}
const stream = {
id: streamId,
name: data.name || `Camera ${streams.size + 1}`,
socketId: socket.id,
status: 'active',
viewers: 0,
quality: quality,
createdAt: new Date().toISOString(),
stats: {
bitrate: acceptance.allocatedBitrate,
fps: 0,
resolution: data.resolution || 'unknown'
}
};
streams.set(streamId, stream);
socket.streamId = streamId;
socket.role = 'streamer';
log(`📹 Streamer registered: ${stream.name} (${streamId}) at ${(acceptance.allocatedBitrate / 1_000_000).toFixed(2)} Mbps`);
// Add to bandwidth manager and reallocate
const newAllocations = bandwidthManager.addStreamer(streamId, quality, socket.id);
// Track initial bitrate for Network Monitor (legacy support)
activeStreams.set(socket.id, acceptance.allocatedBitrate);
broadcastNetworkUsage();
// Notify existing streamers of bandwidth reallocation
newAllocations.forEach((bitrate, sid) => {
const streamerInfo = streams.get(sid);
if (streamerInfo && sid !== streamId) {
const streamerSocket = io.sockets.sockets.get(streamerInfo.socketId);
if (streamerSocket) {
streamerSocket.emit('bandwidth-reallocated', {
newBitrate: bitrate,
reason: 'new_streamer_joined',
activeStreamers: newAllocations.size
});
// Update stats
streamerInfo.stats.bitrate = bitrate;
activeStreams.set(streamerInfo.socketId, bitrate);
}
}
});
// Use HTTP URL for better OBS compatibility
socket.emit('registered', {
streamId,
viewerURL: `${httpURL}/viewer?stream=${streamId}`,
allocatedBitrate: acceptance.allocatedBitrate
});
// Notify all clients about new stream
io.emit('streams-updated', Array.from(streams.values()));
// Broadcast bandwidth status
io.emit('bandwidth-status', bandwidthManager.getStatus());
});
// Register as viewer
socket.on('register-viewer', (data) => {
const { streamId } = data;
socket.streamId = streamId;
socket.role = 'viewer';
if (streams.has(streamId)) {
const stream = streams.get(streamId);
stream.viewers++;
log(`👁️ Viewer connected to: ${stream.name} (${streamId})`);
// Get streamer socket
const streamerSocket = Array.from(io.sockets.sockets.values())
.find(s => s.streamId === streamId && s.role === 'streamer');
if (streamerSocket) {
socket.emit('registered', { streamId, streamerSocketId: streamerSocket.id });
} else {
socket.emit('error', { message: 'Streamer not found' });
}
io.emit('streams-updated', Array.from(streams.values()));
} else {
socket.emit('error', { message: 'Stream not found' });
}
});
// WebRTC Signaling: Offer
socket.on('offer', (data) => {
const { to, offer, streamId } = data;
log(`📤 Forwarding offer from ${socket.id} to ${to}`);
io.to(to).emit('offer', {
from: socket.id,
offer,
streamId
});
});
// WebRTC Signaling: Answer
socket.on('answer', (data) => {
const { to, answer } = data;
log(`📤 Forwarding answer from ${socket.id} to ${to}`);
io.to(to).emit('answer', {
from: socket.id,
answer
});
});
// WebRTC Signaling: ICE Candidate
socket.on('ice-candidate', (data) => {
const { to, candidate } = data;
io.to(to).emit('ice-candidate', {
from: socket.id,
candidate
});
});
// Update stream stats
socket.on('stats-update', (data) => {
// ✅ Update active bitrate for Network Monitor
if (data.role === 'streamer' && data.bitrate) {
activeStreams.set(socket.id, data.bitrate);
broadcastNetworkUsage();
}
if (socket.streamId && streams.has(socket.streamId)) {
const stream = streams.get(socket.streamId);
stream.stats = { ...stream.stats, ...data };
io.emit('streams-updated', Array.from(streams.values()));
}
});
// Bandwidth Test: Start
socket.on('bandwidth-test-start', () => {
log(`🧪 Bandwidth test started: ${socket.id}`);
socket.bandwidthTest = {
startTime: Date.now(),
uploadBytes: 0,
downloadBytes: 0
};
});
// Bandwidth Test: Upload chunk received
socket.on('bandwidth-test-upload', (data) => {
if (socket.bandwidthTest) {
socket.bandwidthTest.uploadBytes += data.size || 0;
}
});
// Bandwidth Test: Download chunk request
socket.on('bandwidth-test-download-request', () => {
if (socket.bandwidthTest) {
// Send a chunk of data back to client
const chunkSize = 64 * 1024; // 64 KB
const chunk = Buffer.alloc(chunkSize);
socket.emit('bandwidth-test-download-chunk', {
chunk: chunk,
size: chunkSize
});
socket.bandwidthTest.downloadBytes += chunkSize;
}
});
// Bandwidth Test: Complete
socket.on('bandwidth-test-complete', (data) => {
if (!socket.bandwidthTest) return;
const duration = Date.now() - socket.bandwidthTest.startTime;
const uploadMbps = (data.uploadBytes * 8) / (duration / 1000) / 1_000_000;
const downloadMbps = (data.downloadBytes * 8) / (duration / 1000) / 1_000_000;
const totalBandwidth = uploadMbps + downloadMbps;
log(`✅ Bandwidth test complete: ${socket.id}`);
log(` Upload: ${uploadMbps.toFixed(2)} Mbps`);
log(` Download: ${downloadMbps.toFixed(2)} Mbps`);
log(` Total: ${totalBandwidth.toFixed(2)} Mbps`);
// Set total available bandwidth in manager
bandwidthManager.setTotalBandwidth(totalBandwidth);
// Send results back to client
socket.emit('bandwidth-test-result', {
upload: uploadMbps,
download: downloadMbps,
total: totalBandwidth
});
// Clean up test data
delete socket.bandwidthTest;
});
// Disconnect
socket.on('disconnect', () => {
log(`❌ Client disconnected: ${socket.id}`);
activeStreams.delete(socket.id);
broadcastNetworkUsage();
if (socket.streamId) {
const stream = streams.get(socket.streamId);
if (socket.role === 'streamer') {
log(`📹 Streamer disconnected: ${stream?.name}`);
streams.delete(socket.streamId);
// Remove from bandwidth manager and reallocate
const newAllocations = bandwidthManager.removeStreamer(socket.streamId);
// Notify remaining streamers of bandwidth reallocation
newAllocations.forEach((bitrate, sid) => {
const streamerInfo = streams.get(sid);
if (streamerInfo) {
const streamerSocket = io.sockets.sockets.get(streamerInfo.socketId);
if (streamerSocket) {
streamerSocket.emit('bandwidth-reallocated', {
newBitrate: bitrate,
reason: 'streamer_disconnected',
activeStreamers: newAllocations.size
});
// Update stats
streamerInfo.stats.bitrate = bitrate;
activeStreams.set(streamerInfo.socketId, bitrate);
}
}
});
// Broadcast updated bandwidth status
io.emit('bandwidth-status', bandwidthManager.getStatus());
} else if (socket.role === 'viewer' && stream) {
stream.viewers = Math.max(0, stream.viewers - 1);
}
io.emit('streams-updated', Array.from(streams.values()));
}
});
});
// Exported functions for programmatic control (Electron GUI)
let serverInstances = { http: null, https: null };
function startServer(logger) {
if (logger) customLogger = logger;
return new Promise((resolve, reject) => {
try {
log('\n🚀 LocalStream Server Starting...\n');
if (useHttps) {
log('🔒 HTTPS Mode (iOS/Safari Compatible)');
log(`📱 Mobile Streamer: ${httpsURL}/mobile`);
log(`💻 Desktop Control: ${httpsURL}/desktop`);
log(`🎥 OBS Viewer: ${httpsURL}/viewer?stream=<stream-id>`);
log(`\n📝 Note: Accept the security warning on first visit\n`);
} else {
log('⚠️ HTTP Mode (Desktop only - iOS will not work)');
log(`📱 Mobile Streamer: ${httpURL}/mobile`);
log(`💻 Desktop Control: ${httpURL}/desktop`);
log(`🎥 OBS Viewer: ${httpURL}/viewer?stream=<stream-id>`);
log(`\n⚠️ To enable iOS support, run: npm run generate-cert\n`);
}
const startPromises = [];
if (useHttps) {
startPromises.push(new Promise((res) => {
serverInstances.https = httpsServer.listen(httpsPort, config.server.host, () => {
log(`✨ HTTPS Server running on port ${httpsPort}`);
log(`🌐 Access from network: ${httpsURL}\n`);
res();
});
}));
startPromises.push(new Promise((res) => {
serverInstances.http = httpServer.listen(httpPort, config.server.host, () => {
log(`📡 HTTP Server running on port ${httpPort} (redirects to HTTPS)`);
res();
});
}));
} else {
startPromises.push(new Promise((res) => {
serverInstances.http = httpServer.listen(httpPort, config.server.host, () => {
log(`✨ HTTP Server running on port ${httpPort}`);
log(`🌐 Access from network: ${httpURL}\n`);
res();
});
}));
}
Promise.all(startPromises).then(() => {
// Start Bonjour/mDNS service after servers are running
if (config.discovery.enabled && !bonjourService) {
const bonjour = new Bonjour.Bonjour();
bonjourService = bonjour.publish({
name: config.discovery.serviceName,
type: config.discovery.serviceType,
port: httpPort,
txt: { path: '/', version: '1.0.0' }
});
log(`🔍 mDNS Service Published: ${config.discovery.serviceName}\n`);
}
resolve({ httpPort, httpsPort: useHttps ? httpsPort : null, localIP });
});
} catch (error) {
reject(error);
}
});
}
function stopServer() {
return new Promise((resolve) => {
log('\n🛑 Shutting down server...');
// Disconnect all Socket.IO clients
if (io) {
io.disconnectSockets();
log('🔌 Disconnected all Socket.IO clients');
}
// Stop Bonjour service
if (bonjourService) {
bonjourService.stop();
bonjourService = null;
log('🔍 Stopped mDNS service');
}
// Close HTTP/HTTPS servers with timeout
const closePromises = [];
if (serverInstances.https) {
closePromises.push(new Promise(res => {
const timeout = setTimeout(() => {
log('⚠️ HTTPS server close timeout, forcing shutdown');
res();
}, 2000);
serverInstances.https.close(() => {
clearTimeout(timeout);
res();
});
}));
}
if (serverInstances.http) {
closePromises.push(new Promise(res => {
const timeout = setTimeout(() => {
log('⚠️ HTTP server close timeout, forcing shutdown');
res();
}, 2000);
serverInstances.http.close(() => {
clearTimeout(timeout);
res();
});
}));
}
Promise.all(closePromises).then(() => {
log('👋 Servers closed');
serverInstances = { http: null, https: null };
resolve();
});
});
}
// CLI mode - only run if executed directly
if (require.main === module) {
startServer(null);
process.on('SIGINT', () => {
stopServer().then(() => process.exit(0));
});
}
// Export for programmatic use (Electron)
module.exports = { startServer, stopServer };