-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
879 lines (734 loc) · 34.4 KB
/
server.py
File metadata and controls
879 lines (734 loc) · 34.4 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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
import json
import logging
import socket
import struct
import time
from typing import Any, Dict, List, Optional, Tuple
import cv2
import numpy as np
import screeninfo
from colorama import Back, Fore, Style, init
init(autoreset=True)
class ColorFormatter(logging.Formatter):
COLORS = {
logging.DEBUG: Fore.YELLOW,
logging.INFO: Fore.CYAN,
logging.WARNING: Fore.YELLOW,
logging.ERROR: Fore.RED,
logging.CRITICAL: Fore.RED + Back.WHITE + Style.BRIGHT,
}
def format(self, record):
message = super().format(record)
color = self.COLORS.get(record.levelno, Fore.WHITE)
return f"{color}{message}{Style.RESET_ALL}"
class ScreenShareServer:
def __init__(self, host: str = '0.0.0.0', port: int = 8080, log_level: int = logging.CRITICAL + 1) -> None:
self.host: str = host
self.port: int = port
self.server_socket: Optional[socket.socket] = None
self.client_socket: Optional[socket.socket] = None
self.client_address: Optional[Tuple[str, int]] = None
self.running: bool = False
# Setup logging [DEFAULT: LOG NOTHING (CRITICAL + 1 = 51)]
self.logger = logging.getLogger(__name__)
self.logger.setLevel(log_level)
self.logger.handlers.clear()
# Only add handler if not logging nothing
if log_level <= logging.CRITICAL:
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.setFormatter(ColorFormatter('%(levelname)s: %(message)s'))
self.logger.addHandler(console_handler)
else:
# Add NullHandler for silent operation
self.logger.addHandler(logging.NullHandler())
# Colorama style
self.C_GREEN: str = Fore.GREEN
self.C_RED: str = Fore.RED
self.C_YELLOW: str = Fore.YELLOW
self.C_CYAN: str = Fore.CYAN
self.C_WHITE: str = Fore.WHITE
self.C_RESET: str = Style.RESET_ALL
# Display info
self.total_displays: int = 1
self.current_display: int = 1
self.display_resolution: str = "Unknown"
self.frame_resolution: str = "Unknown"
self.client_show_mouse: bool = True
self.client_quality: int = 90
# Window settings
self.window_name: str = "Remote Display"
self.window_width: int = 1280
self.window_height: int = 720
# Display settings
self.show_info: bool = True
self.fullScreen: bool = False
self.actual_size: bool = False
self.maintain_aspect: bool = True
# Performance tracking
self.frame_count: int = 0
self.start_time: float = 0.0
self.total_data: int = 0
self.last_stat_display: float = 0.0
# window position tracking
self.window_x: int = 0
self.window_y: int = 0
self.was_fullScreen: bool = False
self.save_window_pos: bool = True
# connection state
self.client_connected: bool = False
self.last_frame_time: float = 0.0
self.offline_display_timeout: float = 3.0 # Show offline message after 3 seconds
# Font
self.font = cv2.FONT_HERSHEY_SIMPLEX
def start(self) -> None:
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(1)
# Always show these UI messages
print(f"{self.C_CYAN}Professional Screen Server on {self.host}:{self.port}{self.C_RESET}")
print(f"{self.C_CYAN}{'=' * 60}{self.C_RESET}")
print(f"{self.C_WHITE}Controls:{self.C_RESET}")
print(f" {self.C_WHITE}Q{self.C_RESET} - Quit")
print(f" {self.C_WHITE}I{self.C_RESET} - Toggle info overlay")
print(f" {self.C_WHITE}M{self.C_RESET} - Toggle mouse display")
print(f" {self.C_WHITE}F{self.C_RESET} - Toggle full screen")
print(f" {self.C_WHITE}A{self.C_RESET} - Toggle actual size")
print(f" {self.C_WHITE}+{self.C_RESET} - Increase window size")
print(f" {self.C_WHITE}-{self.C_RESET} - Decrease window size")
print(f" {self.C_WHITE}R{self.C_RESET} - Reset window size")
print(f" {self.C_WHITE}1-9{self.C_RESET} - Switch displays")
print(f"{self.C_CYAN}{'=' * 60}{self.C_RESET}\n")
print(f"{self.C_CYAN}Waiting for client...{self.C_RESET}")
self.client_socket, self.client_address = self.server_socket.accept()
print(f"{self.C_GREEN}✓ Client connected: {self.client_address}{self.C_RESET}")
self.client_connected = True
ip_address, _ = self.client_address
self.window_name = f"Remote Display - {ip_address}"
self._handle_client()
except KeyboardInterrupt:
print(f"\n{self.C_YELLOW}Server shutdown by user{self.C_RESET}")
except socket.error as e:
print(f"{self.C_RED}✗ Socket error: {e}{self.C_RESET}")
except Exception as e:
self.logger.error(f"Unexpected error: {e}")
finally:
self._cleanup()
def _handle_client(self) -> None:
"""Handle client connection and streaming."""
try:
if self.client_socket:
self.client_socket.settimeout(5.0)
self.client_socket.sendall(b"READY\n")
self.logger.info("Ready signal sent")
self.running = True
self._stream_loop()
except socket.error as e:
self.logger.error(f"Socket error with client: {e}")
except Exception as e:
self.logger.error(f"Error handling client: {e}")
def _stream_loop(self) -> None:
"""Main streaming loop for receiving and displaying frames."""
self.logger.info("Starting stream...")
cv2.namedWindow(self.window_name, cv2.WINDOW_NORMAL)
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
# bring to front and reset
cv2.setWindowProperty(self.window_name, cv2.WND_PROP_TOPMOST, 1)
cv2.setWindowProperty(self.window_name, cv2.WND_PROP_TOPMOST, 0)
# Get initial window position
screen_width = screeninfo.get_monitors()[0].width
screen_height = screeninfo.get_monitors()[0].height
initial_x = (screen_width - self.window_width) // 2
initial_y = (screen_height - self.window_height) // 2
cv2.moveWindow(self.window_name, initial_x, initial_y)
self.window_x, self.window_y = initial_x, initial_y
fps_history: List[float] = []
self.last_frame_time = time.time()
self.frame_count = 0
self.start_time = time.time()
self.last_stat_display = time.time()
print(f"{self.C_GREEN}Stream active. Press Q to quit.{self.C_RESET}\n")
while self.running:
try:
key = cv2.waitKey(1) & 0xFF
if key != 255:
self._process_key_input(key)
if not self.client_connected:
self._display_offline_message()
self._try_reconnect()
continue
frame, metadata = self._receive_frame()
if frame is None:
time_since_last_frame = time.time() - self.last_frame_time
if time_since_last_frame > self.offline_display_timeout:
self.logger.warning("Client disconnected or timeout")
self.client_connected = False
self._close_client_socket()
continue
else:
continue
self.last_frame_time = time.time()
self._update_statistics(frame, metadata)
self._process_frame(frame, metadata, fps_history)
if self.client_socket:
try:
self.client_socket.sendall(b"OK\n")
except (socket.error, ConnectionError):
self.logger.error("Failed to send ACK")
self.client_connected = False
continue
self._update_fps_history(fps_history)
self._display_periodic_stats(fps_history)
except socket.timeout:
continue
except (socket.error, ConnectionError) as e:
self.logger.error(f"Connection lost: {e}")
self.client_connected = False
continue
except cv2.error as e:
self.logger.error(f"OpenCV error: {e}")
break
except Exception as e:
self.logger.error(f"Stream error: {e}")
break
# Spacer
print()
cv2.destroyAllWindows()
self._show_session_summary()
def _process_key_input(self, key: int) -> None:
"""
Process keyboard input for controlling the stream.
Args:
key: ASCII key code from keyboard input
"""
if key == ord('q'):
self.logger.info("Quitting...")
if self.client_connected and self.client_socket:
try:
self.client_socket.sendall(b"STOP\n")
self.logger.info("Sent stop signal to client")
except (socket.error, ConnectionError):
self.logger.debug("Failed to send stop signal")
self.running = False
elif key == ord('i'):
self.show_info = not self.show_info
status = 'ON' if self.show_info else 'OFF'
self.logger.info(f"Info overlay: {status}")
elif key == ord('m'):
if self.client_connected and self.client_socket:
try:
self.client_socket.sendall(b"TOGGLE_MOUSE\n")
self.logger.info("Toggled mouse display")
except (socket.error, ConnectionError):
self.logger.warning("Failed to toggle mouse (client disconnected)")
else:
self.logger.warning("Cannot toggle mouse - client offline")
elif key == ord('f'):
if not self.fullScreen:
# Save current window position before going fullscreen
try:
x, y, w, h = cv2.getWindowImageRect(self.window_name)
self.window_x, self.window_y = x, y
self.was_fullScreen = False
except (cv2.error, TypeError, ValueError) as e:
self.logger.error(f"Could not get window rect: {e}")
cv2.setWindowProperty(self.window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
self.fullScreen = True
self.logger.info("Full Screen: ON")
else:
cv2.setWindowProperty(self.window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_NORMAL)
# Restore window to previous position and size
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
cv2.moveWindow(self.window_name, self.window_x - 8, self.window_y - 31)
# Force a redraw
cv2.waitKey(1)
self.fullScreen = False
self.logger.info("Full Screen: OFF")
elif key == ord('a'):
self.actual_size = not self.actual_size
status = 'ON' if self.actual_size else 'OFF'
self.logger.info(f"Actual size: {status}")
elif key == ord('+') or key == ord('='):
self.window_width = int(self.window_width * 1.1)
self.window_height = int(self.window_height * 1.1)
if not self.fullScreen and not self.actual_size:
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
self.logger.info(f"Window: {self.window_width}x{self.window_height}")
elif key == ord('-'):
self.window_width = max(933, int(self.window_width * 0.9))
self.window_height = max(698, int(self.window_height * 0.9))
if not self.fullScreen and not self.actual_size:
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
self.logger.info(f"Window: {self.window_width}x{self.window_height}")
elif key == ord('r'):
self.window_width = 1280
self.window_height = 720
if not self.fullScreen and not self.actual_size:
cv2.resizeWindow(self.window_name, self.window_width, self.window_height)
self.logger.info(f"Window reset: {self.window_width}x{self.window_height}")
elif ord('1') <= key <= ord('9'):
if self.client_connected and self.client_socket:
display_num = key - ord('0')
if display_num <= self.total_displays:
self.logger.info(f"Switching to display {display_num}")
try:
self.client_socket.sendall(f"SWITCH:{display_num}\n".encode())
except (socket.error, ConnectionError):
self.logger.warning("Switch failed (client disconnected)")
else:
self.logger.warning(f"Invalid display number: {display_num}")
else:
self.logger.warning("Cannot switch displays - client offline")
def _display_offline_message(self) -> None:
"""Display offline message when client is disconnected."""
offline_frame = np.full((720, 1280, 3), 40, dtype=np.uint8)
display_frame = self._prepare_display_frame(offline_frame)
h, w = display_frame.shape[:2]
offline_text = "CLIENT OFFLINE"
(text_width, text_height), _ = cv2.getTextSize(offline_text, self.font, 2, 4)
text_x = (w - text_width) // 2
text_y = (h + text_height) // 2
cv2.putText(display_frame, offline_text, (text_x + 3, text_y + 3),
self.font, 2, (0, 0, 0), 4)
cv2.putText(display_frame, offline_text, (text_x, text_y),
self.font, 2, (100, 100, 255), 4)
subtext = "Waiting for reconnection..."
(sub_width, sub_height), _ = cv2.getTextSize(subtext, self.font, 0.8, 2)
sub_x = (w - sub_width) // 2
sub_y = text_y + 60
cv2.putText(display_frame, subtext, (sub_x, sub_y),
self.font, 0.8, (200, 200, 255), 2)
cv2.imshow(self.window_name, display_frame)
def _try_reconnect(self) -> None:
"""Attempt to reconnect to a new client."""
try:
if self.server_socket:
self.server_socket.settimeout(0.5)
new_client, new_addr = self.server_socket.accept()
self.logger.info(f"New client connected: {new_addr}")
self.client_socket = new_client
self.client_address = new_addr
self.client_connected = True
self.client_socket.sendall(b"READY\n")
self.logger.info("Ready signal sent to new client")
ip_address, _ = new_addr
self.window_name = f"Remote Display - {ip_address}"
except socket.timeout:
pass
except (socket.error, OSError) as e:
self.logger.error(f"Error accepting new connection: {e}")
def _update_statistics(self, frame: np.ndarray, metadata: Optional[Dict[str, Any]]) -> None:
"""
Update frame statistics and metadata.
Args:
frame: Received frame data
metadata: Frame metadata from client
"""
frame_size = frame.nbytes
self.total_data += frame_size
self.frame_count += 1
if metadata:
self.total_displays = metadata.get('total_displays', self.total_displays)
self.current_display = metadata.get('current_display', self.current_display)
self.display_resolution = metadata.get('display_resolution', 'Unknown')
self.frame_resolution = metadata.get('frame_resolution', 'Unknown')
self.client_show_mouse = metadata.get('show_mouse', self.client_show_mouse)
self.client_quality = metadata.get('quality', self.client_quality)
def _process_frame(self, frame: np.ndarray, metadata: Optional[Dict[str, Any]], fps_history: List[float]) -> None:
"""
Process and display a received frame.
Args:
frame: Frame to display
metadata: Frame metadata
fps_history: List of FPS values for averaging
"""
if self.client_show_mouse and metadata:
mouse_x = metadata.get('mouse_x', 0)
mouse_y = metadata.get('mouse_y', 0)
if 0 <= mouse_x < frame.shape[1] and 0 <= mouse_y < frame.shape[0]:
self._draw_mouse_cursor(frame, mouse_x, mouse_y)
display_frame = self._prepare_display_frame(frame)
if self.show_info:
display_frame = self._add_info_overlay(display_frame, fps_history)
cv2.imshow(self.window_name, display_frame)
def _update_fps_history(self, fps_history: List[float]) -> None:
"""
Update FPS history for averaging.
Args:
fps_history: List to update with current FPS
"""
current_time = time.time()
frame_time = current_time - self.last_frame_time
if frame_time > 0:
instant_fps = 1.0 / frame_time
fps_history.append(instant_fps)
if len(fps_history) > 30:
fps_history.pop(0)
def _display_periodic_stats(self, fps_history: List[float]) -> None:
"""
Display periodic statistics every 2 seconds.
Args:
fps_history: List of FPS values for calculation
"""
current_time = time.time()
if current_time - self.last_stat_display >= 2.0:
avg_fps = sum(fps_history) / len(fps_history) if fps_history else 0
# Only show periodic stats if logging at INFO level
if self.logger.level <= logging.INFO:
elapsed = current_time - self.start_time
hours = int(elapsed // 3600)
minutes = int((elapsed % 3600) // 60)
seconds = int(elapsed % 60)
time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
print(f"\r{self.C_WHITE}Display {self.current_display}: {self.display_resolution} | "
f"FPS: {avg_fps:.1f} | Frames: {self.frame_count} | Time: {time_str}{self.C_RESET}",
end="", flush=True)
self.last_stat_display = current_time
def _prepare_display_frame(self, frame: np.ndarray) -> np.ndarray:
"""
Prepare frame for display with appropriate resizing.
Args:
frame: Input frame to prepare
Returns:
Prepared frame for display
"""
if self.fullScreen:
screen_width = cv2.getWindowImageRect(self.window_name)[2]
screen_height = cv2.getWindowImageRect(self.window_name)[3]
target_w, target_h = screen_width, screen_height
elif self.actual_size:
return frame
else:
target_w, target_h = self.window_width, self.window_height
h, w = frame.shape[:2]
if self.maintain_aspect:
scale_w = target_w / w
scale_h = target_h / h
scale = min(scale_w, scale_h)
new_w = int(w * scale)
new_h = int(h * scale)
interpolation = cv2.INTER_AREA if scale < 1.0 else cv2.INTER_LINEAR
resized = cv2.resize(frame, (new_w, new_h), interpolation=interpolation)
if new_w < target_w or new_h < target_h:
top = (target_h - new_h) // 2
bottom = target_h - new_h - top
left = (target_w - new_w) // 2
right = target_w - new_w - left
resized = cv2.copyMakeBorder(resized, top, bottom, left, right,
cv2.BORDER_CONSTANT, value=[40, 40, 40])
return resized
else:
return cv2.resize(frame, (target_w, target_h), interpolation=cv2.INTER_LINEAR)
@staticmethod
def _draw_mouse_cursor(frame: np.ndarray, x: int, y: int) -> None:
"""
Draw mouse cursor on frame.
Args:
frame: Frame to draw on
x: X coordinate of cursor
y: Y coordinate of cursor
"""
cv2.circle(frame, (x, y), 7, (255, 255, 255), -1)
cv2.circle(frame, (x, y), 5, (0, 120, 255), -1)
cv2.circle(frame, (x, y), 7, (0, 0, 0), 1)
cv2.line(frame, (x, y - 9), (x, y + 9), (0, 0, 0), 1)
cv2.line(frame, (x - 9, y), (x + 9, y), (0, 0, 0), 1)
@staticmethod
def _format_time(seconds: float) -> str:
"""
Format elapsed time in HH:MM:SS format.
Args:
seconds: Time in seconds
Returns:
Formatted time string (HH:MM:SS)
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds_int = int(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{seconds_int:02d}"
def _add_info_overlay(self, frame: np.ndarray, fps_history: List[float]) -> np.ndarray:
"""
Add information overlay to frame.
Args:
frame: Frame to add overlay to
fps_history: FPS history for calculation
Returns:
Frame with info overlay
"""
h, w = frame.shape[:2]
overlay = frame.copy()
bar_height = 65
cv2.rectangle(overlay, (0, 0), (w, bar_height), (20, 20, 30), -1)
frame = cv2.addWeighted(overlay, 0.85, frame, 0.15, 0)
avg_fps = sum(fps_history) / len(fps_history) if fps_history else 0
if avg_fps > 15:
fps_color = (100, 255, 100)
elif avg_fps > 8:
fps_color = (100, 255, 255)
else:
fps_color = (100, 100, 255)
left_margin = 15
y_base = 40
display_text = f"Display {self.current_display}/{self.total_displays}"
cv2.putText(frame, display_text,
(left_margin, y_base),
self.font, 0.8, (240, 240, 240), 2)
fps_text = f"FPS: {avg_fps:.1f}"
cv2.putText(frame, fps_text,
(left_margin + 200, y_base),
self.font, 0.8, fps_color, 2)
center_x = w // 2
res_text = f"{self.display_resolution}"
(text_width, _), _ = cv2.getTextSize(res_text, self.font, 0.8, 2)
cv2.putText(frame, res_text,
(center_x - text_width // 2, y_base),
self.font, 0.8, (200, 220, 200), 2)
right_margin = 15
mouse_status = f"Mouse: {'ON' if self.client_show_mouse else 'OFF'}"
(mouse_width, _), _ = cv2.getTextSize(mouse_status, self.font, 0.6, 1)
cv2.putText(frame, mouse_status,
(w - mouse_width - right_margin, y_base - 10),
self.font, 0.6, (200, 200, 240), 1)
quality_text = f"Quality: {self.client_quality}"
(quality_width, _), _ = cv2.getTextSize(quality_text, self.font, 0.6, 1)
cv2.putText(frame, quality_text,
(w - quality_width - right_margin, y_base + 15),
self.font, 0.6, (200, 240, 200), 1)
bottom_margin = 20
bottom_bar_height = 30
overlay_bottom = frame.copy()
cv2.rectangle(overlay_bottom, (0, h - bottom_bar_height), (w, h), (20, 20, 30), -1)
frame = cv2.addWeighted(overlay_bottom, 0.85, frame, 0.15, 0)
# Bottom Background
bottom_bar_top = h - bottom_bar_height - bottom_margin
bottom_bar_bottom = h - bottom_margin
overlay_bottom = frame.copy()
cv2.rectangle(overlay_bottom, (0, bottom_bar_top), (w, bottom_bar_bottom), (20, 20, 30), -1)
frame = cv2.addWeighted(overlay_bottom, 0.85, frame, 0.15, 0)
# Bottom Padding
bottom_y = h - bottom_margin - 8
# Left: Frame count
frame_info = f"Frame: {self.frame_count}"
cv2.putText(frame, frame_info,
(left_margin, bottom_y),
self.font, 0.6, (150, 220, 150), 1)
# Center: Time
elapsed = time.time() - self.start_time
time_str = self._format_time(elapsed)
time_text = f"Time: {time_str}"
(time_width, _), _ = cv2.getTextSize(time_text, self.font, 0.6, 1)
time_x = (w - time_width) // 2
cv2.putText(frame, time_text,
(time_x, bottom_y),
self.font, 0.6, (220, 220, 255), 1)
# Right: Controls
controls = "Q:Quit | I:Info | M:Mouse | F:Full | A:Actual"
(controls_width, _), _ = cv2.getTextSize(controls, self.font, 0.5, 1)
cv2.putText(frame, controls,
(w - controls_width - 10, bottom_y),
self.font, 0.5, (180, 180, 200), 1)
# Status indicator above bottom bar
status_color = (100, 255, 100) if self.client_connected else (100, 100, 255)
status_text = "ONLINE" if self.client_connected else "OFFLINE"
(status_width, _), _ = cv2.getTextSize(status_text, self.font, 0.6, 1)
cv2.putText(frame, status_text,
(w - status_width - 10, bottom_y - 20),
self.font, 0.6, status_color, 1)
return frame
def _receive_frame(self) -> Tuple[Optional[np.ndarray], Optional[Dict[str, Any]]]:
"""
Receive a frame and metadata from client.
Returns:
Tuple of (frame, metadata) or (None, None) on failure
"""
try:
if not self.client_socket:
return None, None
metadata_size_data = self._recv_exact(4)
if not metadata_size_data:
self.logger.debug("No metadata size received")
return None, None
metadata_size = struct.unpack("I", metadata_size_data)[0]
self.logger.debug(f"Metadata size: {metadata_size} bytes")
metadata_bytes = self._recv_exact(metadata_size)
if not metadata_bytes:
self.logger.debug("No metadata received")
return None, None
try:
metadata = json.loads(metadata_bytes.decode('utf-8'))
self.logger.debug(f"Metadata received: {metadata}")
except (json.JSONDecodeError, UnicodeDecodeError) as e:
self.logger.warning(f"Failed to decode metadata: {e}")
metadata = {}
frame_size_data = self._recv_exact(4)
if not frame_size_data:
self.logger.debug("No frame size received")
return None, None
frame_size = struct.unpack("I", frame_size_data)[0]
self.logger.debug(f"Frame size: {frame_size} bytes")
frame_data = self._recv_exact(frame_size)
if not frame_data:
self.logger.debug("No frame data received")
return None, None
frame = cv2.imdecode(np.frombuffer(frame_data, np.uint8), cv2.IMREAD_COLOR)
if frame is None:
self.logger.warning("Failed to decode frame")
return None, None
self.logger.debug(f"Frame decoded: {frame.shape[1]}x{frame.shape[0]}")
return frame, metadata
except (socket.error, ConnectionError) as e:
self.logger.debug(f"Connection error while receiving frame: {e}")
return None, None
except struct.error as e:
self.logger.warning(f"Error unpacking frame data: {e}")
return None, None
except cv2.error as e:
self.logger.warning(f"Error decoding frame: {e}")
return None, None
except Exception as e:
self.logger.error(f"Unexpected error receiving frame: {e}")
return None, None
def _recv_exact(self, size: int) -> Optional[bytes]:
"""
Receive exact number of bytes from socket.
Args:
size: Number of bytes to receive
Returns:
Received bytes or None on failure/timeout
"""
data = b""
timeout = 3.0
start = time.time()
while len(data) < size and (time.time() - start) < timeout:
try:
if not self.client_socket:
return None
chunk = self.client_socket.recv(min(65536, size - len(data)))
if not chunk:
return None
data += chunk
except socket.timeout:
continue
except (socket.error, ConnectionError) as e:
self.logger.debug(f"Socket error while receiving: {e}")
return None
if len(data) < size:
self.logger.debug(f"Timeout receiving data: got {len(data)} of {size} bytes")
return None
return data
def _show_session_summary(self) -> None:
"""Display session summary statistics."""
elapsed = time.time() - self.start_time
fps = self.frame_count / elapsed if elapsed > 0 else 0
# Format time for display
hours = int(elapsed // 3600)
minutes = int((elapsed % 3600) // 60)
seconds = int(elapsed % 60)
time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
# Always show session summary
print(f"\n{self.C_CYAN}{'=' * 60}{self.C_RESET}")
print(f"{self.C_YELLOW}SESSION SUMMARY{self.C_RESET}")
print(f"{self.C_CYAN}{'=' * 60}{self.C_RESET}")
print(f"{self.C_WHITE}Total frames:{self.C_RESET} {self.C_GREEN}{self.frame_count}{self.C_RESET}")
print(f"{self.C_WHITE}Duration:{self.C_RESET} {self.C_CYAN}{time_str}{self.C_RESET}")
print(f"{self.C_WHITE}Average FPS:{self.C_RESET} {self.C_CYAN}{fps:.1f}{self.C_RESET}")
print(
f"{self.C_WHITE}Final display:{self.C_RESET} {self.C_CYAN}{self.current_display}/{self.total_displays}{self.C_RESET}")
print(f"{self.C_WHITE}Display resolution:{self.C_RESET} {self.C_CYAN}{self.display_resolution}{self.C_RESET}")
print(
f"{self.C_WHITE}Total data:{self.C_RESET} {self.C_CYAN}{self.total_data / 1024 / 1024:.1f} MB{self.C_RESET}"
)
print(f"{self.C_CYAN}{'=' * 60}{self.C_RESET}")
def _close_client_socket(self) -> None:
"""Close client socket if it exists."""
if self.client_socket:
try:
self.client_socket.close()
self.logger.debug("Client socket closed")
except (socket.error, OSError) as e:
self.logger.debug(f"Error closing client socket: {e}")
def _cleanup(self) -> None:
"""Cleanup all resources and connections."""
self.logger.info("Cleaning up...")
self.running = False
self._close_client_socket()
if self.server_socket:
try:
self.server_socket.close()
self.logger.debug("Server socket closed")
except (socket.error, OSError) as e:
self.logger.debug(f"Error closing server socket: {e}")
cv2.destroyAllWindows()
self.logger.info("Server stopped")
def parse_args() -> Dict[str, Any]:
"""Parse command line arguments."""
import sys
import logging
# Default: LOG NOTHING (CRITICAL + 1 = 51)
_args = {
'host': '0.0.0.0',
'port': 8080,
'log_level': logging.CRITICAL + 1 # Default: log nothing
}
log_level_map = {
'silent': logging.CRITICAL + 1,
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL,
}
for arg in sys.argv[1:]:
if arg.startswith('--log-level=') or arg.startswith('-l='):
level_str = arg.split('=')[1].lower()
if level_str in log_level_map:
_args['log_level'] = log_level_map[level_str]
else:
try:
level_num = int(level_str)
if logging.DEBUG <= level_num <= logging.CRITICAL:
_args['log_level'] = level_num
elif level_num > logging.CRITICAL:
# Values > CRITICAL mean log nothing
_args['log_level'] = level_num
else:
print(f"{Fore.RED}Invalid log level number: {level_num}.{Style.RESET_ALL}")
except ValueError:
print(
f"{Fore.RED}Invalid log level: {level_str}. Must be one of: {', '.join(log_level_map.keys())}{Style.RESET_ALL}")
elif arg.startswith('--host='):
_args['host'] = arg.split('=')[1]
elif arg.startswith('--port='):
try:
_args['port'] = int(arg.split('=')[1])
except ValueError:
print(f"{Fore.RED}Invalid port number: {arg.split('=')[1]}{Style.RESET_ALL}")
elif arg in ['-h', '--help']:
print(f"{Fore.CYAN}Usage: python server.py [options]{Style.RESET_ALL}")
print(f"{Fore.WHITE}Options:{Style.RESET_ALL}")
print(f" --host=HOST Server hostname (default: 0.0.0.0)")
print(f" --port=PORT Server port (default: 8080)")
print(f" --log-level=LEVEL Log level: silent, debug, info, warning, error, critical (default: silent)")
print(f" -l=LEVEL Short form for log level")
print(f" -h, --help Show this help message")
print(f"\n{Fore.WHITE}Log levels:{Style.RESET_ALL}")
print(f" {Fore.CYAN}silent{Style.RESET_ALL}: {Fore.WHITE}No logging output (default){Style.RESET_ALL}")
print(f" {Fore.CYAN}debug{Style.RESET_ALL}: {Fore.YELLOW}Detailed debugging information{Style.RESET_ALL}")
print(f" {Fore.CYAN}info{Style.RESET_ALL}: {Fore.CYAN}General information{Style.RESET_ALL}")
print(f" {Fore.CYAN}warning{Style.RESET_ALL}: {Fore.YELLOW}Warning messages{Style.RESET_ALL}")
print(f" {Fore.CYAN}error{Style.RESET_ALL}: {Fore.RED}Error messages{Style.RESET_ALL}")
print(
f" {Fore.CYAN}critical{Style.RESET_ALL}: {Fore.RED}{Style.BRIGHT}Critical errors only{Style.RESET_ALL}"
)
sys.exit(0)
return _args
if __name__ == "__main__":
args = parse_args()
server = ScreenShareServer(
host=args['host'],
port=args['port'],
log_level=args['log_level']
)
server.start()