-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2351 lines (1980 loc) · 88 KB
/
main.py
File metadata and controls
2351 lines (1980 loc) · 88 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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
PyDisplayWindow Pro - Ultra High Quality Display Capture Stream Application
A professional screen capture application with ultra-high quality rendering,
smooth 60-144 FPS streaming, hardware acceleration support, and advanced
features for streaming platforms like Discord, TikTok, OBS, etc.
Author: PyDisplayWindow Team
Version: 2.0.0 Pro
"""
import sys
import json
import os
import signal
import logging
import time
import threading
import queue
from pathlib import Path
from typing import Optional, List, Dict, Tuple, Callable, Union
from dataclasses import dataclass, asdict, field
from enum import Enum, auto
from collections import deque
import ctypes
from ctypes import wintypes
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger('PyDisplayWindowPro')
import numpy as np
from PIL import Image, ImageFilter, ImageEnhance
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QPushButton, QComboBox, QDialog, QDialogButtonBox,
QGroupBox, QSpinBox, QCheckBox, QSlider, QStatusBar, QMenuBar,
QMenu, QFileDialog, QMessageBox, QFrame, QSizePolicy, QGridLayout,
QProgressBar, QTabWidget, QRadioButton, QButtonGroup
)
from PyQt6.QtCore import (
Qt, QTimer, pyqtSignal, QObject, QThread, QSize, QSettings,
QMutex, QWaitCondition, QRect
)
from PyQt6.QtGui import (
QImage, QPixmap, QIcon, QKeySequence, QAction, QFont,
QCloseEvent, QResizeEvent, QPaintEvent, QPainter, QPen, QColor,
QSurfaceFormat, QOpenGLContext
)
from ctypes import wintypes
# Optional high-performance libraries
PIL_AVAILABLE = False
try:
from PIL import ImageGrab, Image
PIL_AVAILABLE = True
except ImportError:
pass
try:
import cv2
CV2_AVAILABLE = True
except ImportError:
CV2_AVAILABLE = False
logger.warning("OpenCV not available. Advanced processing disabled.")
try:
import dxcam
DXCAM_AVAILABLE = True
logger.info("dxcam (DXGI) available — ultra-fast hardware capture enabled")
except Exception:
DXCAM_AVAILABLE = False
logger.warning("dxcam not available. Falling back to mss/PIL.")
try:
import mss
MSS_AVAILABLE = True
logger.info("mss available as fallback capture backend")
except ImportError:
MSS_AVAILABLE = False
# =============================================================================
# Configuration & Data Classes
# =============================================================================
class CaptureMode(Enum):
FULL_SCREEN = "full_screen"
CUSTOM_REGION = "custom_region"
class QualityPreset(Enum):
PERFORMANCE = auto()
BALANCED = auto()
HIGH_QUALITY = auto()
ULTRA = auto()
MAXIMUM = auto()
@dataclass
class DisplayInfo:
"""Information about a connected display/monitor."""
index: int
name: str
width: int
height: int
x: int
y: int
is_primary: bool
refresh_rate: int = 60
def __str__(self) -> str:
primary_tag = " [Primary]" if self.is_primary else ""
return f"{self.name}{primary_tag} ({self.width}x{self.height} @ {self.refresh_rate}Hz)"
@dataclass
class CaptureSettings:
"""Advanced capture settings for professional quality."""
# Frame Rate
target_fps: int = 60
vsync_enabled: bool = True
adaptive_sync: bool = True
# Quality
quality_preset: QualityPreset = QualityPreset.HIGH_QUALITY
scale_factor: float = 1.0
use_lanczos_scaling: bool = True
enable_sharpening: bool = True
sharpening_amount: float = 1.2
color_enhancement: bool = True
# Buffering
buffer_size: int = 3
enable_triple_buffering: bool = True
max_frame_latency: int = 2
# Hardware
use_hardware_acceleration: bool = True
gpu_decode: bool = False
prefer_gpu_rendering: bool = True
# Cursor
capture_cursor: bool = True
cursor_smoothing: bool = True
cursor_shadow: bool = True
cursor_scale: float = 1.0
# Performance
dynamic_quality_adjust: bool = True
min_quality_threshold: float = 0.85
drop_frames_on_lag: bool = True
# Display
enable_hdr_support: bool = False
color_space: str = "sRGB"
bit_depth: int = 8
def to_dict(self) -> Dict:
data = asdict(self)
data['quality_preset'] = self.quality_preset.name
return data
@classmethod
def from_dict(cls, data: Dict) -> 'CaptureSettings':
if 'quality_preset' in data:
data['quality_preset'] = QualityPreset[data['quality_preset']]
return cls(**data)
@dataclass
class AppSettings:
"""Application settings and preferences."""
# Core settings
target_fps: int = 60
capture_mode: str = "full_screen"
selected_display: int = 0
# UI settings
show_fps: bool = True
always_on_top: bool = False # DEFAULT: OFF - User can enable if needed
maintain_aspect_ratio: bool = True
enable_preview: bool = True
presentation_mode: bool = True
# Legacy quality (deprecated, use capture_settings)
quality: int = 95
scale_factor: float = 1.0
# Advanced capture settings
capture_settings: CaptureSettings = field(default_factory=CaptureSettings)
# Logging
enable_logging: bool = True
log_level: str = "INFO"
def to_dict(self) -> Dict:
data = asdict(self)
data['capture_settings'] = self.capture_settings.to_dict()
return data
@classmethod
def from_dict(cls, data: Dict) -> 'AppSettings':
if 'capture_settings' in data:
data['capture_settings'] = CaptureSettings.from_dict(data['capture_settings'])
else:
# Create default settings
data['capture_settings'] = CaptureSettings()
return cls(**data)
# =============================================================================
# High-Performance Frame Buffer
# =============================================================================
class FrameBuffer:
"""Triple-buffered frame storage for smooth playback."""
def __init__(self, size: int = 3):
self.size = max(2, min(size, 5))
self._buffers: deque = deque(maxlen=self.size)
self._mutex = threading.Lock() # Use threading.Lock instead of QMutex
self._write_index = 0
self._read_index = 0
self._frame_count = 0
def write(self, frame: np.ndarray, timestamp: float) -> bool:
"""Write frame to buffer. Returns True if successful."""
with self._mutex:
if len(self._buffers) >= self.size:
# Drop oldest frame
self._buffers.popleft()
# Store frame with metadata
frame_data = {
'frame': frame,
'timestamp': timestamp,
'index': self._frame_count
}
self._buffers.append(frame_data)
self._frame_count += 1
return True
def read(self) -> Optional[Tuple[np.ndarray, float]]:
"""Read latest frame from buffer."""
with self._mutex:
if not self._buffers:
return None
# Return the most recent frame
latest = self._buffers[-1]
return latest['frame'], latest['timestamp']
def get_latency(self) -> float:
"""Get current buffer latency in frames."""
with self._mutex:
return len(self._buffers)
def clear(self):
"""Clear all buffered frames."""
with self._mutex:
self._buffers.clear()
self._frame_count = 0
# =============================================================================
# Hardware Acceleration Detector
# =============================================================================
class HardwareAcceleration:
"""Detect and manage hardware acceleration capabilities."""
@staticmethod
def check_d3d11_support() -> bool:
"""Check for Direct3D 11 support on Windows."""
try:
# Load D3D11 library
d3d11 = ctypes.windll.d3d11
return True
except Exception:
return False
@staticmethod
def check_opengl_support() -> bool:
"""Check for OpenGL support."""
try:
from PyQt6.QtOpenGL import QOpenGLVersionProfile
return True
except ImportError:
return False
@staticmethod
def get_optimal_settings() -> Dict:
"""Get optimal hardware acceleration settings."""
return {
'd3d11_available': HardwareAcceleration.check_d3d11_support(),
'opengl_available': HardwareAcceleration.check_opengl_support(),
'recommended_buffer': 3,
'use_gpu_scaling': True,
'prefer_native_capture': True
}
# =============================================================================
# Display Detection (Enhanced)
# =============================================================================
class DisplayManager:
"""Manages display/monitor detection with refresh rate info."""
@staticmethod
def get_refresh_rate(device_name: Optional[str] = None) -> int:
"""Get the refresh rate of a display using Windows API."""
try:
user32 = ctypes.windll.user32
class DEVMODEW(ctypes.Structure):
_fields_ = [
("dmDeviceName", wintypes.WCHAR * 32),
("dmSpecVersion", wintypes.WORD),
("dmDriverVersion", wintypes.WORD),
("dmSize", wintypes.WORD),
("dmDriverExtra", wintypes.WORD),
("dmFields", wintypes.DWORD),
("dmPositionX", wintypes.LONG),
("dmPositionY", wintypes.LONG),
("dmDisplayOrientation", wintypes.DWORD),
("dmDisplayFixedOutput", wintypes.DWORD),
("dmColor", wintypes.SHORT),
("dmDuplex", wintypes.SHORT),
("dmYResolution", wintypes.SHORT),
("dmTTOption", wintypes.SHORT),
("dmCollate", wintypes.SHORT),
("dmFormName", wintypes.WCHAR * 32),
("dmLogPixels", wintypes.WORD),
("dmBitsPerPel", wintypes.DWORD),
("dmPelsWidth", wintypes.DWORD),
("dmPelsHeight", wintypes.DWORD),
("dmDisplayFlags", wintypes.DWORD),
("dmDisplayFrequency", wintypes.DWORD),
("dmICMMethod", wintypes.DWORD),
("dmICMIntent", wintypes.DWORD),
("dmMediaType", wintypes.DWORD),
("dmDitherType", wintypes.DWORD),
("dmReserved1", wintypes.DWORD),
("dmReserved2", wintypes.DWORD),
("dmPanningWidth", wintypes.DWORD),
("dmPanningHeight", wintypes.DWORD),
]
ENUM_CURRENT_SETTINGS = -1
dm = DEVMODEW()
dm.dmSize = ctypes.sizeof(DEVMODEW)
dev = device_name if device_name else None
if user32.EnumDisplaySettingsW(dev, ENUM_CURRENT_SETTINGS, ctypes.byref(dm)):
hz = int(dm.dmDisplayFrequency)
if hz > 0:
return hz
except Exception as e:
logger.debug(f"Could not get refresh rate: {e}")
return 60
@staticmethod
def get_available_displays() -> List[DisplayInfo]:
"""Get list of all available displays using Windows API."""
displays = []
try:
user32 = ctypes.windll.user32
class RECT(ctypes.Structure):
_fields_ = [("left", wintypes.LONG), ("top", wintypes.LONG), ("right", wintypes.LONG), ("bottom", wintypes.LONG)]
class MONITORINFOEXW(ctypes.Structure):
_fields_ = [
("cbSize", wintypes.DWORD),
("rcMonitor", RECT),
("rcWork", RECT),
("dwFlags", wintypes.DWORD),
("szDevice", wintypes.WCHAR * 32),
]
MONITORINFOF_PRIMARY = 0x00000001
class DEVMODEW(ctypes.Structure):
_fields_ = [
("dmDeviceName", wintypes.WCHAR * 32),
("dmSpecVersion", wintypes.WORD),
("dmDriverVersion", wintypes.WORD),
("dmSize", wintypes.WORD),
("dmDriverExtra", wintypes.WORD),
("dmFields", wintypes.DWORD),
("dmPositionX", wintypes.LONG),
("dmPositionY", wintypes.LONG),
("dmDisplayOrientation", wintypes.DWORD),
("dmDisplayFixedOutput", wintypes.DWORD),
("dmColor", wintypes.SHORT),
("dmDuplex", wintypes.SHORT),
("dmYResolution", wintypes.SHORT),
("dmTTOption", wintypes.SHORT),
("dmCollate", wintypes.SHORT),
("dmFormName", wintypes.WCHAR * 32),
("dmLogPixels", wintypes.WORD),
("dmBitsPerPel", wintypes.DWORD),
("dmPelsWidth", wintypes.DWORD),
("dmPelsHeight", wintypes.DWORD),
("dmDisplayFlags", wintypes.DWORD),
("dmDisplayFrequency", wintypes.DWORD),
("dmICMMethod", wintypes.DWORD),
("dmICMIntent", wintypes.DWORD),
("dmMediaType", wintypes.DWORD),
("dmDitherType", wintypes.DWORD),
("dmReserved1", wintypes.DWORD),
("dmReserved2", wintypes.DWORD),
("dmPanningWidth", wintypes.DWORD),
("dmPanningHeight", wintypes.DWORD),
]
ENUM_CURRENT_SETTINGS = -1
found: List[Tuple[str, int, int, int, int, bool, int]] = []
def _get_settings(device: str) -> Optional[DEVMODEW]:
dm = DEVMODEW()
dm.dmSize = ctypes.sizeof(DEVMODEW)
if user32.EnumDisplaySettingsW(device, ENUM_CURRENT_SETTINGS, ctypes.byref(dm)):
return dm
return None
MONITORENUMPROC = ctypes.WINFUNCTYPE(
wintypes.BOOL,
wintypes.HMONITOR,
wintypes.HDC,
ctypes.POINTER(RECT),
wintypes.LPARAM,
)
def enum_proc(hmonitor, hdc, lprect, lparam):
mi = MONITORINFOEXW()
mi.cbSize = ctypes.sizeof(MONITORINFOEXW)
if not user32.GetMonitorInfoW(hmonitor, ctypes.byref(mi)):
return True
dev = mi.szDevice
dm = _get_settings(dev)
if dm is None:
rc = mi.rcMonitor
left = int(rc.left)
top = int(rc.top)
width = int(rc.right - rc.left)
height = int(rc.bottom - rc.top)
hz = DisplayManager.get_refresh_rate(dev)
else:
left = int(dm.dmPositionX)
top = int(dm.dmPositionY)
width = int(dm.dmPelsWidth)
height = int(dm.dmPelsHeight)
hz = int(dm.dmDisplayFrequency) if int(dm.dmDisplayFrequency) > 0 else DisplayManager.get_refresh_rate(dev)
is_primary = bool(mi.dwFlags & MONITORINFOF_PRIMARY)
found.append((dev, left, top, width, height, is_primary, hz))
return True
user32.EnumDisplayMonitors(None, None, MONITORENUMPROC(enum_proc), 0)
if not found:
raise RuntimeError("No monitors detected")
for i, (dev, left, top, width, height, is_primary, hz) in enumerate(found, start=1):
displays.append(DisplayInfo(
index=i,
name=f"{dev} ({width}x{height} @ {hz}Hz)",
width=width,
height=height,
x=left,
y=top,
is_primary=is_primary,
refresh_rate=hz,
))
except Exception as e:
logger.error(f"Error detecting displays: {e}")
user32 = ctypes.windll.user32
width = int(user32.GetSystemMetrics(0))
height = int(user32.GetSystemMetrics(1))
hz = DisplayManager.get_refresh_rate(None)
displays.append(DisplayInfo(
index=1,
name=f"Primary ({width}x{height} @ {hz}Hz)",
width=width,
height=height,
x=0,
y=0,
is_primary=True,
refresh_rate=hz,
))
return displays
@staticmethod
def get_primary_display() -> Optional[DisplayInfo]:
"""Get the primary display."""
displays = DisplayManager.get_available_displays()
for display in displays:
if display.is_primary:
return display
return displays[0] if displays else None
@staticmethod
def get_recommended_fps(display_info: DisplayInfo) -> int:
"""Get recommended FPS based on display refresh rate."""
if display_info.refresh_rate >= 144:
return 144
elif display_info.refresh_rate >= 120:
return 120
elif display_info.refresh_rate >= 60:
return 60
else:
return display_info.refresh_rate
# =============================================================================
# Screen Capture Engine
# =============================================================================
class CaptureSignals(QObject):
"""Signals emitted by the capture worker."""
frame_captured = pyqtSignal(np.ndarray)
capture_error = pyqtSignal(str)
fps_updated = pyqtSignal(float)
performance_warning = pyqtSignal(str)
quality_adjusted = pyqtSignal(float)
request_window_opacity = pyqtSignal(float)
class CaptureWorker(QThread):
"""Professional capture worker with advanced features."""
def __init__(self, display_info: DisplayInfo, settings: Union[int, 'CaptureSettings'] = 60, capture_cursor: bool = True):
super().__init__()
self.signals = CaptureSignals()
self.display_info = display_info
self._lock = threading.Lock()
# Support both old (int) and new (CaptureSettings) interface
if isinstance(settings, CaptureSettings):
self.capture_settings = settings
self.target_fps = settings.target_fps
self.capture_cursor = settings.capture_cursor
else:
# Legacy support: settings is just FPS integer
self.target_fps = settings
self.capture_cursor = capture_cursor
self.capture_settings = CaptureSettings(target_fps=settings, capture_cursor=capture_cursor)
self.is_running = False
self.frame_time = 1.0 / self.target_fps
def set_cursor_capture(self, enabled: bool):
"""Enable/disable cursor capture."""
with self._lock:
self.capture_cursor = enabled
def _draw_cursor(self, img: np.ndarray, monitor: Dict) -> np.ndarray:
"""
Draw mouse cursor onto a screenshot (numpy RGB array).
Uses dual-pass GDI technique: render cursor on black AND white
background, then derive the true cursor pixels and alpha mask.
This correctly handles monochrome (arrow) and color cursors alike.
"""
try:
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
# --- 1. Query cursor state ---
class CURSORINFO(ctypes.Structure):
_fields_ = [
("cbSize", wintypes.DWORD),
("flags", wintypes.DWORD),
("hCursor", wintypes.HCURSOR),
("ptScreenPos", wintypes.POINT),
]
ci = CURSORINFO()
ci.cbSize = ctypes.sizeof(CURSORINFO)
if not user32.GetCursorInfo(ctypes.byref(ci)):
return img
if not (ci.flags & 0x1): # CURSOR_SHOWING
return img
class ICONINFO(ctypes.Structure):
_fields_ = [
("fIcon", wintypes.BOOL),
("xHotspot", wintypes.DWORD),
("yHotspot", wintypes.DWORD),
("hbmMask", wintypes.HBITMAP),
("hbmColor", wintypes.HBITMAP),
]
ii = ICONINFO()
if not user32.GetIconInfo(ci.hCursor, ctypes.byref(ii)):
return img
hot_x = int(ii.xHotspot)
hot_y = int(ii.yHotspot)
pos_x = int(ci.ptScreenPos.x) - int(monitor["left"]) - hot_x
pos_y = int(ci.ptScreenPos.y) - int(monitor["top"]) - hot_y
CSIZE = 64 # cursor render size
# --- 2. BITMAPINFOHEADER for top-down 32-bit DIB ---
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", wintypes.DWORD),
("biWidth", wintypes.LONG),
("biHeight", wintypes.LONG),
("biPlanes", wintypes.WORD),
("biBitCount", wintypes.WORD),
("biCompression", wintypes.DWORD),
("biSizeImage", wintypes.DWORD),
("biXPelsPerMeter", wintypes.LONG),
("biYPelsPerMeter", wintypes.LONG),
("biClrUsed", wintypes.DWORD),
("biClrImportant", wintypes.DWORD),
]
def _render_on_bg(fill_rop: int) -> Optional[np.ndarray]:
"""Render cursor over a solid background (BLACKNESS or WHITENESS)."""
hdc_s = user32.GetDC(None)
hdc_m = gdi32.CreateCompatibleDC(hdc_s)
bmi = BITMAPINFOHEADER()
bmi.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.biWidth = CSIZE
bmi.biHeight = -CSIZE # top-down
bmi.biPlanes = 1
bmi.biBitCount = 32
bmi.biCompression = 0 # BI_RGB
bits = ctypes.c_void_p()
hbm = gdi32.CreateDIBSection(hdc_m, ctypes.byref(bmi), 0,
ctypes.byref(bits), None, 0)
if not hbm:
gdi32.DeleteDC(hdc_m)
user32.ReleaseDC(None, hdc_s)
return None
old = gdi32.SelectObject(hdc_m, hbm)
gdi32.PatBlt(hdc_m, 0, 0, CSIZE, CSIZE, fill_rop)
user32.DrawIconEx(hdc_m, 0, 0, ci.hCursor,
CSIZE, CSIZE, 0, None, 0x0003) # DI_NORMAL
buf = (ctypes.c_ubyte * (CSIZE * CSIZE * 4)).from_address(bits.value)
arr = np.frombuffer(buf, dtype=np.uint8).reshape((CSIZE, CSIZE, 4)).copy()
gdi32.SelectObject(hdc_m, old)
gdi32.DeleteObject(hbm)
gdi32.DeleteDC(hdc_m)
user32.ReleaseDC(None, hdc_s)
return arr # BGRA
BLACKNESS = 0x00000042
WHITENESS = 0x00FF0062
on_black = _render_on_bg(BLACKNESS)
on_white = _render_on_bg(WHITENESS)
# free GDI resources
try:
if ii.hbmMask: gdi32.DeleteObject(ii.hbmMask)
if ii.hbmColor: gdi32.DeleteObject(ii.hbmColor)
except Exception:
pass
if on_black is None or on_white is None:
return img
# --- 3. Dual-pass: recover cursor colour + alpha ---
# Over black: result = cursor_color * alpha
# Over white: result = cursor_color * alpha + (1-alpha)*255
# Therefore: alpha = 1 - (on_white - on_black) / 255
# color = on_black / alpha
b_f = on_black[:, :, :3].astype(np.float32) # BGR
w_f = on_white[:, :, :3].astype(np.float32)
alpha_f = 1.0 - np.clip((w_f - b_f) / 255.0, 0.0, 1.0)
alpha_mask = alpha_f.max(axis=2, keepdims=True) # (H,W,1)
with np.errstate(divide='ignore', invalid='ignore'):
color_bgr = np.where(
alpha_mask > 0.02,
np.clip(b_f / np.maximum(alpha_mask, 0.02), 0, 255),
b_f
)
# BGR -> RGB
cursor_rgb = color_bgr[:, :, ::-1].astype(np.uint8)
# --- 4. Composite onto the screenshot ---
h, w = img.shape[:2]
x0 = max(0, pos_x); y0 = max(0, pos_y)
x1 = min(w, pos_x+CSIZE); y1 = min(h, pos_y+CSIZE)
if x0 >= x1 or y0 >= y1:
return img
cx0 = x0 - pos_x; cy0 = y0 - pos_y
cx1 = cx0+(x1-x0); cy1 = cy0+(y1-y0)
roi = img[y0:y1, x0:x1].astype(np.float32)
cur = cursor_rgb[cy0:cy1, cx0:cx1].astype(np.float32)
alp = alpha_mask[cy0:cy1, cx0:cx1]
img[y0:y1, x0:x1] = np.clip(
cur * alp + roi * (1.0 - alp), 0, 255
).astype(np.uint8)
return img
except Exception as e:
logger.debug(f"Cursor draw error: {e}")
return img
def _apply_quality_enhancements(self, img: np.ndarray) -> np.ndarray:
"""
Lightweight quality pass: only a gentle unsharp mask when sharpening
is requested. CLAHE is intentionally removed — it distorts text and
anti-aliased elements, making them look blurry / noisy.
Maximum quality = zero processing (native pixels are best).
"""
if not CV2_AVAILABLE:
return img
# Maximum / Ultra preset: return native pixels untouched
if self.capture_settings.quality_preset in (
QualityPreset.MAXIMUM, QualityPreset.ULTRA
):
return img
try:
if self.capture_settings.enable_sharpening:
# Gentle unsharp mask (much softer than the old 9-kernel)
blurred = cv2.GaussianBlur(img, (0, 0), sigmaX=1.0)
img = cv2.addWeighted(img, 1.3, blurred, -0.3, 0)
except Exception as e:
logger.debug(f"Enhancement error: {e}")
return img
def _lanczos_resize(self, img: np.ndarray, target_size: Tuple[int, int]) -> np.ndarray:
"""High-quality Lanczos resampling."""
if CV2_AVAILABLE:
return cv2.resize(img, target_size, interpolation=cv2.INTER_LANCZOS4)
return img
def set_display(self, display_info: DisplayInfo):
"""Change the display being captured."""
with self._lock:
self.display_info = display_info
def set_fps(self, fps: int):
"""Update target FPS."""
with self._lock:
self.target_fps = fps
self.frame_time = 1.0 / fps
def stop(self):
"""Stop the capture loop."""
self.is_running = False
self.wait(1000) # Wait up to 1 second for thread to finish
# ------------------------------------------------------------------
# Backend-specific capture helpers
# ------------------------------------------------------------------
def _capture_frame_dxcam(self, camera) -> Optional[np.ndarray]:
"""Grab one frame via dxcam (DXGI Desktop Duplication)."""
frame = camera.get_latest_frame()
return frame # already RGB numpy uint8, or None if no new frame
def _capture_frame_mss(self, sct, mon_dict: Dict) -> np.ndarray:
"""Grab one frame via mss (fast GDI)."""
shot = sct.grab(mon_dict)
img = np.array(shot) # BGRA
return img[:, :, 2::-1].copy() # -> RGB
def _capture_frame_pil(self, bbox: Tuple) -> Optional[np.ndarray]:
"""Grab one frame via Pillow ImageGrab (slowest, always available)."""
try:
pil_img = ImageGrab.grab(bbox=bbox, all_screens=True)
except TypeError:
pil_img = ImageGrab.grab(bbox)
img = np.asarray(pil_img)
if img.size == 0:
return None
if len(img.shape) == 2:
img = np.stack([img, img, img], axis=-1)
elif img.shape[2] == 4:
img = img[:, :, :3]
return img.copy()
def _emit_fps(self, frame_count: int, fps_time: float) -> Tuple[int, float]:
elapsed = time.time() - fps_time
if elapsed >= 1.0:
self.signals.fps_updated.emit(frame_count / elapsed)
return 0, time.time()
return frame_count, fps_time
# ------------------------------------------------------------------
# Main run loop
# ------------------------------------------------------------------
def run(self):
"""Main capture loop — tries dxcam → mss → PIL in order."""
self.is_running = True
with self._lock:
display = self.display_info
capture_cursor = self.capture_cursor
settings = self.capture_settings
monitor_dict = {
"left": display.x,
"top": display.y,
"width": display.width,
"height": display.height,
}
bbox = (display.x, display.y,
display.x + display.width,
display.y + display.height)
# ---- Choose backend ----
if DXCAM_AVAILABLE:
self._run_dxcam(display, settings, capture_cursor)
elif MSS_AVAILABLE:
self._run_mss(monitor_dict, settings, capture_cursor)
elif PIL_AVAILABLE:
self._run_pil(bbox, settings, capture_cursor)
else:
self.signals.capture_error.emit(
"No capture backend available. Install dxcam or mss.")
# ---- dxcam backend (DXGI, hardware, true 60-144 FPS) ----
def _run_dxcam(self, display: DisplayInfo, settings: 'CaptureSettings',
capture_cursor: bool):
import dxcam
camera = None
try:
# Find the dxcam output index matching our monitor
# dxcam output_idx corresponds to monitor index (0-based)
output_idx = max(0, display.index - 1)
camera = dxcam.create(
output_idx=output_idx,
output_color="RGB"
)
# with_cursor not supported on all dxcam builds; catch gracefully
try:
camera = dxcam.create(
output_idx=output_idx,
output_color="RGB"
)
except Exception:
pass
target_fps = settings.target_fps
camera.start(target_fps=target_fps, video_mode=True)
logger.info(f"dxcam started: output_idx={output_idx}, "
f"target_fps={target_fps}")
frame_count = 0
fps_time = time.time()
monitor_dict = {
"left": display.x,
"top": display.y,
"width": display.width,
"height": display.height,
}
while self.is_running:
with self._lock:
capture_cursor = self.capture_cursor
settings = self.capture_settings
img = camera.get_latest_frame()
if img is None:
# No new frame yet — yield and retry
time.sleep(0.001)
continue
# img is already RGB uint8 from dxcam
img = img.copy()
# Apply enhancements (lightweight only)
img = self._apply_quality_enhancements(img)
# Draw cursor (dxcam doesn't include it by default)
if capture_cursor:
img = self._draw_cursor(img, monitor_dict)
self.signals.frame_captured.emit(img)
frame_count += 1
frame_count, fps_time = self._emit_fps(frame_count, fps_time)
except Exception as e:
import traceback
logger.error(f"dxcam error: {e}\n{traceback.format_exc()}")
self.signals.capture_error.emit(
f"dxcam failed: {e} — falling back to mss")
# Graceful fallback
if MSS_AVAILABLE:
monitor_dict = {
"left": display.x,
"top": display.y,
"width": display.width,
"height": display.height,
}
self._run_mss(monitor_dict, settings, capture_cursor)
finally:
try:
if camera is not None:
camera.stop()
del camera
except Exception:
pass
# ---- mss backend (fast GDI, ~30-60 FPS) ----
def _run_mss(self, monitor_dict: Dict, settings: 'CaptureSettings',
capture_cursor: bool):
import mss as mss_module
logger.info("Using mss capture backend")
frame_count = 0
fps_time = time.time()
with mss_module.mss() as sct:
while self.is_running:
loop_start = time.time()
with self._lock:
capture_cursor = self.capture_cursor
settings = self.capture_settings
try:
img = self._capture_frame_mss(sct, monitor_dict)
img = self._apply_quality_enhancements(img)
if capture_cursor:
img = self._draw_cursor(img, monitor_dict)
self.signals.frame_captured.emit(img)
frame_count += 1
frame_count, fps_time = self._emit_fps(frame_count, fps_time)
except Exception as e:
logger.error(f"mss capture error: {e}")
time.sleep(0.05)
continue
elapsed = time.time() - loop_start
sleep_time = self.frame_time - elapsed
if sleep_time > 0:
time.sleep(sleep_time)
# ---- PIL / ImageGrab backend (reliable fallback, ~10-20 FPS) ----
def _run_pil(self, bbox: Tuple, settings: 'CaptureSettings',
capture_cursor: bool):
if not PIL_AVAILABLE:
self.signals.capture_error.emit("No capture backend available.")
return
logger.info("Using PIL ImageGrab capture backend (slowest)")
monitor_dict = {
"left": bbox[0], "top": bbox[1],
"width": bbox[2]-bbox[0],
"height": bbox[3]-bbox[1],
}
frame_count = 0
fps_time = time.time()
while self.is_running:
loop_start = time.time()
with self._lock:
capture_cursor = self.capture_cursor
settings = self.capture_settings
try:
img = self._capture_frame_pil(bbox)
if img is None:
time.sleep(0.05)
continue
img = self._apply_quality_enhancements(img)
if capture_cursor:
img = self._draw_cursor(img, monitor_dict)
self.signals.frame_captured.emit(img)
frame_count += 1
frame_count, fps_time = self._emit_fps(frame_count, fps_time)
except Exception as e:
import traceback
logger.error(f"PIL capture error: {e}\n{traceback.format_exc()}")
time.sleep(0.1)