├── .github ├── FUNDING.yml └── workflow │ └── workflow.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── benchmarks ├── bettercam_capture.py ├── bettercam_max_fps.py ├── d3dshot_max_fps.py ├── dxcam_capture.py ├── dxcam_max_fps.py └── mss_max_fps.py ├── bettercam ├── __init__.py ├── _libs │ ├── __init__.py │ ├── d3d11.py │ ├── dxgi.py │ └── user32.py ├── bettercam.py ├── core │ ├── __init__.py │ ├── device.py │ ├── duplicator.py │ ├── output.py │ └── stagesurf.py ├── processor │ ├── __init__.py │ ├── base.py │ ├── cupy_processor.py │ └── numpy_processor.py └── util │ ├── __init__.py │ ├── io.py │ └── timer.py ├── examples ├── capture_to_video.py └── instant_replay.py ├── images └── banner.png ├── pyproject.toml ├── setup.cfg └── setup.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [qfc9] 4 | -------------------------------------------------------------------------------- /.github/workflow/workflow.yml: -------------------------------------------------------------------------------- 1 | # - name: pypi-publish 2 | # uses: pypa/gh-action-pypi-publish@v1.8.10 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Local tests 132 | .test/ -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ### 0.0.5 2 | - Fixed black screen for rotated display 3 | - Added delay on start to prevent black screenshot 4 | - Fixed capture mode for color = "GRAY" 5 | ### 0.0.2 6 | - Refactoring 7 | - Screen capturing w/ target FPS use CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 8 | ### 0.0.1 9 | - Initial commit 10 | - Basic features: screenshot 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Rain 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📸 **BetterCam** 🚀 2 | ![World's Best AI Aimbot Banner](images/banner.png) 3 | 4 | [![Pull Requests Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat)](http://makeapullrequest.com) 5 | > ***🌟 World's Fastest Python Screenshot Library for Windows 🐍*** 6 | 7 | ```python 8 | import bettercam 9 | camera = bettercam.create() 10 | camera.grab() 11 | ``` 12 | 13 | ## 🌈 Introduction 14 | BetterCam is the World's 🌏 Fastest Publicly available Python screenshot library for Windows, boasting 240Hz+ capturing using the Desktop Duplication API 🖥️💨. Born from [DXCam](https://github.com/ra1nty/DXcam), it shines in deep learning pipelines for FPS games, outpacing other Python solutions like [python-mss](https://github.com/BoboTiG/python-mss) and [D3DShot](https://github.com/SerpentAI/D3DShot/). 15 | 16 | BetterCam's superpowers include: 17 | - 🚅 Insanely fast screen capturing (> 240Hz) 18 | - 🎮 Capture from Direct3D exclusive full-screen apps without interruption, even during alt+tab. 19 | - 🔧 Auto-adjusts to scaled / stretched resolutions. 20 | - 🎯 Precise FPS targeting for Video output. 21 | - 👌 Smooth NumPy, OpenCV, PyTorch integration, etc. 22 | 23 | > ***💞 Community contributions warmly invited!*** 24 | 25 | ## 🛠️ Installation 26 | ### From PyPI: 27 | ```bash 28 | pip install bettercam 29 | ``` 30 | 31 | **Note:** 🧩 OpenCV is needed by BetterCam for color space conversion. Install it with `pip install opencv-python` if not yet available. 32 | 33 | 34 | ## 📚 Usage 35 | Each monitor is paired with a `BetterCam` instance. 36 | To get started: 37 | ```python 38 | import bettercam 39 | camera = bettercam.create() # Primary monitor's BetterCam instance 40 | ``` 41 | ### 📷 Screenshot 42 | For a quick snap, call `.grab`: 43 | ```python 44 | frame = camera.grab() 45 | ``` 46 | `frame` is a `numpy.ndarray` in the `(Height, Width, 3[RGB])` format by default. Note: `.grab` may return `None` if there's no update since the last `.grab`. 47 | 48 | To display your screenshot: 49 | ```python 50 | from PIL import Image 51 | Image.fromarray(frame).show() 52 | ``` 53 | For a specific region, provide the `region` parameter with a tuple for the bounding box coordinates: 54 | ```python 55 | left, top = (1920 - 640) // 2, (1080 - 640) // 2 56 | right, bottom = left + 640, top + 640 57 | region = (left, top, right, bottom) 58 | frame = camera.grab(region=region) # A 640x640x3 numpy ndarray snapshot 59 | ``` 60 | 61 | ### 📹 Screen Capture 62 | Start and stop screen capture with `.start` and `.stop`: 63 | ```python 64 | camera.start(region=(left, top, right, bottom)) # Capture a region (optional) 65 | camera.is_capturing # True 66 | # ... Your Code 67 | camera.stop() 68 | camera.is_capturing # False 69 | ``` 70 | 71 | ### 🔄 Retrieving Captured Data 72 | When capturing, grab the latest frame with `.get_latest_frame`: 73 | ```python 74 | camera.start() 75 | for i in range(1000): 76 | image = camera.get_latest_frame() # Waits for a new frame 77 | camera.stop() 78 | ``` 79 | 80 | ## ⚙️ Advanced Usage & Notes 81 | ### 🖥️ Multiple Monitors / GPUs 82 | ```python 83 | cam1, cam2, cam3 = [bettercam.create(device_idx=d, output_idx=o) for d, o in [(0, 0), (0, 1), (1, 1)]] 84 | img1, img2, img3 = [cam.grab() for cam in (cam1, cam2, cam3)] 85 | ``` 86 | To list devices and outputs: 87 | ```pycon 88 | >>> import bettercam 89 | >>> bettercam.device_info() 90 | >>> bettercam.output_info() 91 | ``` 92 | 93 | ### 🎨 Output Format 94 | Select your color mode when creating a BetterCam instance: 95 | ```python 96 | bettercam.create(output_idx=0, output_color="BGRA") 97 | ``` 98 | We support "RGB", "RGBA", "BGR", "BGRA", "GRAY" (for grayscale). Right now only `numpy.ndarray` shapes are supported: `(Height, Width, Channels)`. 99 | 100 | ### 🔄 Video Buffer 101 | Frames go into a fixed-size ring buffer. Customize its max length with `max_buffer_len` on creation: 102 | ```python 103 | camera = bettercam.create(max_buffer_len=512) 104 | ``` 105 | 106 | ### 🎥 Target FPS 107 | For precise FPS targeting, we use the high-resolution `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`: 108 | ```python 109 | camera.start(target_fps=120) # Ideally, not beyond 240Hz. 110 | ``` 111 | 112 | ### 🔄 Video Mode 113 | For constant framerate video recording, use `video_mode=True` during `.start`: 114 | ```python 115 | # Example: Record a 5-second, 120Hz video 116 | camera.start(target_fps=target_fps, video_mode=True) 117 | # ... Video writing code goes here 118 | ``` 119 | 120 | ### 🛠️ Resource Management 121 | Call `.release` to stop captures and free resources. Manual deletion also possible: 122 | ```python 123 | del camera 124 | ``` 125 | 126 | ## 📊 Benchmarks 127 | ### Max FPS Achievement: 128 | ```python 129 | cam = bettercam.create() 130 | # ... Benchmarking code... 131 | ``` 132 | | | BetterCam Nvidia GPU :checkered_flag: | BetterCam :checkered_flag: | DXCam | python-mss | D3DShot | 133 | |---------|---------------------------------------|--------------------------|--------|------------|---------| 134 | | Avg FPS | 111.667 | 123.667 | 39 | 34.667 | N/A | 135 | | Std Dev | 0.889 | 1.778 | 1.333 | 2.222 | N/A | 136 | 137 | ### FPS Targeting: 138 | ```python 139 | # ... Sample code to test target FPS ... 140 | ``` 141 | | Target/Result | BetterCam Nvidia GPU :checkered_flag: | BetterCam :checkered_flag: | DXCam | python-mss | D3DShot | 142 | |---------------|---------------------------------------|--------------------------|-------|------------|---------| 143 | | 120fps | 111.667, 0.889 | 88.333, 2.444 | 36.667, 0.889 | N/A | N/A | 144 | | 60fps | 60, 0 | 60, 0 | 35, 5.3 | N/A | N/A | 145 | 146 | ## 📝 Referenced Work 147 | - [DXCam](https://github.com/ra1nty/DXcam): Our origin story. 148 | - [D3DShot](https://github.com/SerpentAI/D3DShot/): Provided foundational ctypes. 149 | - [OBS Studio](https://github.com/obsproject/obs-studio): A treasure trove of knowledge. 150 | 151 | [^1]: [Preemption (computing)](https://en.wikipedia.org/wiki/Preemption_(computing)) 152 | [^2]: [Time.sleep precision improvement](https://github.com/python/cpython/issues/65501) -------------------------------------------------------------------------------- /benchmarks/bettercam_capture.py: -------------------------------------------------------------------------------- 1 | import time 2 | import bettercam 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[BetterCam] Capture benchmark" 11 | 12 | fps = 0 13 | camera = bettercam.create(output_idx=0, output_color="BGRA") 14 | camera.start(target_fps=60, video_mode=True) 15 | for i in range(1000): 16 | image = camera.get_latest_frame() 17 | camera.stop() 18 | del camera 19 | -------------------------------------------------------------------------------- /benchmarks/bettercam_max_fps.py: -------------------------------------------------------------------------------- 1 | import time 2 | import bettercam 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[BetterCam] FPS benchmark" 11 | start_time = time.perf_counter() 12 | 13 | 14 | fps = 0 15 | cam = bettercam.create() 16 | start = time.perf_counter() 17 | while fps < 1000: 18 | frame = cam.grab(region=region) 19 | if frame is not None: 20 | fps += 1 21 | 22 | end_time = time.perf_counter() - start_time 23 | 24 | print(f"{title}: {fps/end_time}") 25 | del cam 26 | -------------------------------------------------------------------------------- /benchmarks/d3dshot_max_fps.py: -------------------------------------------------------------------------------- 1 | import time 2 | import d3dshot 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[D3DShot] FPS benchmark" 11 | start_time = time.perf_counter() 12 | 13 | fps = 0 14 | 15 | 16 | sct = d3dshot.create(capture_output="numpy") 17 | 18 | 19 | start = time.perf_counter() 20 | while fps < 1000: 21 | frame = sct.screenshot(region) 22 | if frame is not None: 23 | fps += 1 24 | 25 | 26 | end_time = time.perf_counter() - start_time 27 | 28 | print(f"{title}: {fps/end_time}") 29 | sct.stop() 30 | -------------------------------------------------------------------------------- /benchmarks/dxcam_capture.py: -------------------------------------------------------------------------------- 1 | import time 2 | import dxcam 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[dxcam] Capture benchmark" 11 | 12 | fps = 0 13 | camera = dxcam.create(output_idx=0, output_color="BGRA") 14 | camera.start(target_fps=60, video_mode=True) 15 | for i in range(1000): 16 | image = camera.get_latest_frame() 17 | camera.stop() 18 | del camera 19 | -------------------------------------------------------------------------------- /benchmarks/dxcam_max_fps.py: -------------------------------------------------------------------------------- 1 | import time 2 | import dxcam 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[dxcam] FPS benchmark" 11 | start_time = time.perf_counter() 12 | 13 | 14 | fps = 0 15 | cam = dxcam.create() 16 | start = time.perf_counter() 17 | while fps < 1000: 18 | frame = cam.grab(region=region) 19 | if frame is not None: 20 | fps += 1 21 | 22 | end_time = time.perf_counter() - start_time 23 | 24 | print(f"{title}: {fps/end_time}") 25 | del cam 26 | -------------------------------------------------------------------------------- /benchmarks/mss_max_fps.py: -------------------------------------------------------------------------------- 1 | import time 2 | import mss 3 | 4 | 5 | TOP = 0 6 | LEFT = 0 7 | RIGHT = 1920 8 | BOTTOM = 1080 9 | region = (LEFT, TOP, RIGHT, BOTTOM) 10 | title = "[MSS] FPS benchmark" 11 | start_time = time.perf_counter() 12 | 13 | 14 | fps = 0 15 | sct = mss.mss() 16 | start = time.perf_counter() 17 | while fps < 1000: 18 | frame = sct.grab(region) 19 | if frame is not None: 20 | fps += 1 21 | 22 | 23 | end_time = time.perf_counter() - start_time 24 | 25 | print(f"{title}: {fps/end_time}") 26 | -------------------------------------------------------------------------------- /bettercam/__init__.py: -------------------------------------------------------------------------------- 1 | import weakref 2 | import time 3 | from bettercam.bettercam import BetterCam, Output, Device 4 | from bettercam.util.io import ( 5 | enum_dxgi_adapters, 6 | get_output_metadata, 7 | ) 8 | 9 | 10 | class Singleton(type): 11 | _instances = {} 12 | 13 | def __call__(cls, *args, **kwargs): 14 | if cls not in cls._instances: 15 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 16 | else: 17 | print(f"Only 1 instance of {cls.__name__} is allowed.") 18 | 19 | return cls._instances[cls] 20 | 21 | 22 | class DXFactory(metaclass=Singleton): 23 | 24 | _camera_instances = weakref.WeakValueDictionary() 25 | 26 | def __init__(self) -> None: 27 | p_adapters = enum_dxgi_adapters() 28 | self.devices, self.outputs = [], [] 29 | for p_adapter in p_adapters: 30 | device = Device(p_adapter) 31 | p_outputs = device.enum_outputs() 32 | if len(p_outputs) != 0: 33 | self.devices.append(device) 34 | self.outputs.append([Output(p_output) for p_output in p_outputs]) 35 | self.output_metadata = get_output_metadata() 36 | 37 | def create( 38 | self, 39 | device_idx: int = 0, 40 | output_idx: int = None, 41 | region: tuple = None, 42 | output_color: str = "RGB", 43 | nvidia_gpu: bool = False, 44 | max_buffer_len: int = 64, 45 | ): 46 | device = self.devices[device_idx] 47 | if output_idx is None: 48 | # Select Primary Output 49 | output_idx = [ 50 | idx 51 | for idx, metadata in enumerate( 52 | self.output_metadata.get(output.devicename) 53 | for output in self.outputs[device_idx] 54 | ) 55 | if metadata[1] 56 | ][0] 57 | instance_key = (device_idx, output_idx) 58 | if instance_key in self._camera_instances: 59 | print( 60 | "".join( 61 | ( 62 | f"You already created a BetterCam Instance for Device {device_idx}--Output {output_idx}!\n", 63 | "Returning the existed instance...\n", 64 | "To change capture parameters you can manually delete the old object using `del obj`.", 65 | ) 66 | ) 67 | ) 68 | return self._camera_instances[instance_key] 69 | 70 | output = self.outputs[device_idx][output_idx] 71 | output.update_desc() 72 | camera = BetterCam( 73 | output=output, 74 | device=device, 75 | region=region, 76 | output_color=output_color, 77 | nvidia_gpu=nvidia_gpu, 78 | max_buffer_len=max_buffer_len, 79 | ) 80 | self._camera_instances[instance_key] = camera 81 | time.sleep(0.1) # Fix for https://github.com/ra1nty/BetterCam/issues/31 82 | return camera 83 | 84 | def device_info(self) -> str: 85 | ret = "" 86 | for idx, device in enumerate(self.devices): 87 | ret += f"Device[{idx}]:{device}\n" 88 | return ret 89 | 90 | def output_info(self) -> str: 91 | ret = "" 92 | for didx, outputs in enumerate(self.outputs): 93 | for idx, output in enumerate(outputs): 94 | ret += f"Device[{didx}] Output[{idx}]: " 95 | ret += f"Res:{output.resolution} Rot:{output.rotation_angle}" 96 | ret += f" Primary:{self.output_metadata.get(output.devicename)[1]}\n" 97 | return ret 98 | 99 | def clean_up(self): 100 | for _, camera in self._camera_instances.items(): 101 | camera.release() 102 | 103 | 104 | __factory = DXFactory() 105 | 106 | 107 | def create( 108 | device_idx: int = 0, 109 | output_idx: int = None, 110 | region: tuple = None, 111 | output_color: str = "RGB", 112 | nvidia_gpu: bool = False, 113 | max_buffer_len: int = 64, 114 | ): 115 | return __factory.create( 116 | device_idx=device_idx, 117 | output_idx=output_idx, 118 | region=region, 119 | output_color=output_color, 120 | nvidia_gpu=nvidia_gpu, 121 | max_buffer_len=max_buffer_len, 122 | ) 123 | 124 | 125 | def device_info(): 126 | return __factory.device_info() 127 | 128 | 129 | def output_info(): 130 | return __factory.output_info() 131 | -------------------------------------------------------------------------------- /bettercam/_libs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RootKit-Org/BetterCam/b4d6b0e7dbcea58f85eb61f3324268749142d53e/bettercam/_libs/__init__.py -------------------------------------------------------------------------------- /bettercam/_libs/d3d11.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import ctypes.wintypes as wintypes 3 | import comtypes 4 | 5 | 6 | D3D11_CPU_ACCESS_WRITE = 0x10000 7 | D3D11_CPU_ACCESS_READ = 0x20000 8 | 9 | D3D_FEATURE_LEVEL_9_1 = 0x9100 10 | D3D_FEATURE_LEVEL_9_2 = 0x9200 11 | D3D_FEATURE_LEVEL_9_3 = 0x9300 12 | D3D_FEATURE_LEVEL_10_0 = 0xA000 13 | D3D_FEATURE_LEVEL_10_1 = 0xA100 14 | D3D_FEATURE_LEVEL_11_0 = 0xB000 15 | D3D_FEATURE_LEVEL_11_1 = 0xB100 16 | 17 | D3D11_USAGE_DEFAULT = 0 18 | D3D11_USAGE_IMMUTABLE = 1 19 | D3D11_USAGE_DYNAMIC = 2 20 | D3D11_USAGE_STAGING = 3 21 | 22 | DXGI_FORMAT_B8G8R8A8_UNORM = 87 23 | 24 | 25 | class DXGI_SAMPLE_DESC(ctypes.Structure): 26 | _fields_ = [ 27 | ("Count", wintypes.UINT), 28 | ("Quality", wintypes.UINT), 29 | ] 30 | 31 | 32 | class D3D11_BOX(ctypes.Structure): 33 | _fields_ = [ 34 | ("left", wintypes.UINT), 35 | ("top", wintypes.UINT), 36 | ("front", wintypes.UINT), 37 | ("right", wintypes.UINT), 38 | ("bottom", wintypes.UINT), 39 | ("back", wintypes.UINT), 40 | ] 41 | 42 | 43 | class D3D11_TEXTURE2D_DESC(ctypes.Structure): 44 | _fields_ = [ 45 | ("Width", wintypes.UINT), 46 | ("Height", wintypes.UINT), 47 | ("MipLevels", wintypes.UINT), 48 | ("ArraySize", wintypes.UINT), 49 | ("Format", wintypes.UINT), 50 | ("SampleDesc", DXGI_SAMPLE_DESC), 51 | ("Usage", wintypes.UINT), 52 | ("BindFlags", wintypes.UINT), 53 | ("CPUAccessFlags", wintypes.UINT), 54 | ("MiscFlags", wintypes.UINT), 55 | ] 56 | 57 | 58 | class ID3D11DeviceChild(comtypes.IUnknown): 59 | _iid_ = comtypes.GUID("{1841e5c8-16b0-489b-bcc8-44cfb0d5deae}") 60 | _methods_ = [ 61 | comtypes.STDMETHOD(None, "GetDevice"), 62 | comtypes.STDMETHOD(comtypes.HRESULT, "GetPrivateData"), 63 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateData"), 64 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateDataInterface"), 65 | ] 66 | 67 | 68 | class ID3D11Resource(ID3D11DeviceChild): 69 | _iid_ = comtypes.GUID("{dc8e63f3-d12b-4952-b47b-5e45026a862d}") 70 | _methods_ = [ 71 | comtypes.STDMETHOD(None, "GetType"), 72 | comtypes.STDMETHOD(None, "SetEvictionPriority"), 73 | comtypes.STDMETHOD(wintypes.UINT, "GetEvictionPriority"), 74 | ] 75 | 76 | 77 | class ID3D11Texture2D(ID3D11Resource): 78 | _iid_ = comtypes.GUID("{6f15aaf2-d208-4e89-9ab4-489535d34f9c}") 79 | _methods_ = [ 80 | comtypes.STDMETHOD(None, "GetDesc", [ctypes.POINTER(D3D11_TEXTURE2D_DESC)]), 81 | ] 82 | 83 | 84 | class ID3D11DeviceContext(ID3D11DeviceChild): 85 | _iid_ = comtypes.GUID("{c0bfa96c-e089-44fb-8eaf-26f8796190da}") 86 | _methods_ = [ 87 | comtypes.STDMETHOD(None, "VSSetConstantBuffers"), 88 | comtypes.STDMETHOD(None, "PSSetShaderResources"), 89 | comtypes.STDMETHOD(None, "PSSetShader"), 90 | comtypes.STDMETHOD(None, "PSSetSamplers"), 91 | comtypes.STDMETHOD(None, "VSSetShader"), 92 | comtypes.STDMETHOD(None, "DrawIndexed"), 93 | comtypes.STDMETHOD(None, "Draw"), 94 | comtypes.STDMETHOD(comtypes.HRESULT, "Map"), 95 | comtypes.STDMETHOD(None, "Unmap"), 96 | comtypes.STDMETHOD(None, "PSSetConstantBuffers"), 97 | comtypes.STDMETHOD(None, "IASetInputLayout"), 98 | comtypes.STDMETHOD(None, "IASetVertexBuffers"), 99 | comtypes.STDMETHOD(None, "IASetIndexBuffer"), 100 | comtypes.STDMETHOD(None, "DrawIndexedInstanced"), 101 | comtypes.STDMETHOD(None, "DrawInstanced"), 102 | comtypes.STDMETHOD(None, "GSSetConstantBuffers"), 103 | comtypes.STDMETHOD(None, "GSSetShader"), 104 | comtypes.STDMETHOD(None, "IASetPrimitiveTopology"), 105 | comtypes.STDMETHOD(None, "VSSetShaderResources"), 106 | comtypes.STDMETHOD(None, "VSSetSamplers"), 107 | comtypes.STDMETHOD(None, "Begin"), 108 | comtypes.STDMETHOD(None, "End"), 109 | comtypes.STDMETHOD(comtypes.HRESULT, "GetData"), 110 | comtypes.STDMETHOD(None, "SetPredication"), 111 | comtypes.STDMETHOD(None, "GSSetShaderResources"), 112 | comtypes.STDMETHOD(None, "GSSetSamplers"), 113 | comtypes.STDMETHOD(None, "OMSetRenderTargets"), 114 | comtypes.STDMETHOD(None, "OMSetRenderTargetsAndUnorderedAccessViews"), 115 | comtypes.STDMETHOD(None, "OMSetBlendState"), 116 | comtypes.STDMETHOD(None, "OMSetDepthStencilState"), 117 | comtypes.STDMETHOD(None, "SOSetTargets"), 118 | comtypes.STDMETHOD(None, "DrawAuto"), 119 | comtypes.STDMETHOD(None, "DrawIndexedInstancedIndirect"), 120 | comtypes.STDMETHOD(None, "DrawInstancedIndirect"), 121 | comtypes.STDMETHOD(None, "Dispatch"), 122 | comtypes.STDMETHOD(None, "DispatchIndirect"), 123 | comtypes.STDMETHOD(None, "RSSetState"), 124 | comtypes.STDMETHOD(None, "RSSetViewports"), 125 | comtypes.STDMETHOD(None, "RSSetScissorRects"), 126 | comtypes.STDMETHOD( 127 | None, 128 | "CopySubresourceRegion", 129 | [ 130 | ctypes.POINTER(ID3D11Resource), 131 | wintypes.UINT, 132 | wintypes.UINT, 133 | wintypes.UINT, 134 | wintypes.UINT, 135 | ctypes.POINTER(ID3D11Resource), 136 | wintypes.UINT, 137 | ctypes.POINTER(D3D11_BOX), 138 | ], 139 | ), 140 | comtypes.STDMETHOD( 141 | None, 142 | "CopyResource", 143 | [ctypes.POINTER(ID3D11Resource), ctypes.POINTER(ID3D11Resource)], 144 | ), 145 | comtypes.STDMETHOD(None, "UpdateSubresource"), 146 | comtypes.STDMETHOD(None, "CopyStructureCount"), 147 | comtypes.STDMETHOD(None, "ClearRenderTargetView"), 148 | comtypes.STDMETHOD(None, "ClearUnorderedAccessViewUint"), 149 | comtypes.STDMETHOD(None, "ClearUnorderedAccessViewFloat"), 150 | comtypes.STDMETHOD(None, "ClearDepthStencilView"), 151 | comtypes.STDMETHOD(None, "GenerateMips"), 152 | comtypes.STDMETHOD(None, "SetResourceMinLOD"), 153 | comtypes.STDMETHOD(wintypes.FLOAT, "GetResourceMinLOD"), 154 | comtypes.STDMETHOD(None, "ResolveSubresource"), 155 | comtypes.STDMETHOD(None, "ExecuteCommandList"), 156 | comtypes.STDMETHOD(None, "HSSetShaderResources"), 157 | comtypes.STDMETHOD(None, "HSSetShader"), 158 | comtypes.STDMETHOD(None, "HSSetSamplers"), 159 | comtypes.STDMETHOD(None, "HSSetConstantBuffers"), 160 | comtypes.STDMETHOD(None, "DSSetShaderResources"), 161 | comtypes.STDMETHOD(None, "DSSetShader"), 162 | comtypes.STDMETHOD(None, "DSSetSamplers"), 163 | comtypes.STDMETHOD(None, "DSSetConstantBuffers"), 164 | comtypes.STDMETHOD(None, "CSSetShaderResources"), 165 | comtypes.STDMETHOD(None, "CSSetUnorderedAccessViews"), 166 | comtypes.STDMETHOD(None, "CSSetShader"), 167 | comtypes.STDMETHOD(None, "CSSetSamplers"), 168 | comtypes.STDMETHOD(None, "CSSetConstantBuffers"), 169 | comtypes.STDMETHOD(None, "VSGetConstantBuffers"), 170 | comtypes.STDMETHOD(None, "PSGetShaderResources"), 171 | comtypes.STDMETHOD(None, "PSGetShader"), 172 | comtypes.STDMETHOD(None, "PSGetSamplers"), 173 | comtypes.STDMETHOD(None, "VSGetShader"), 174 | comtypes.STDMETHOD(None, "PSGetConstantBuffers"), 175 | comtypes.STDMETHOD(None, "IAGetInputLayout"), 176 | comtypes.STDMETHOD(None, "IAGetVertexBuffers"), 177 | comtypes.STDMETHOD(None, "IAGetIndexBuffer"), 178 | comtypes.STDMETHOD(None, "GSGetConstantBuffers"), 179 | comtypes.STDMETHOD(None, "GSGetShader"), 180 | comtypes.STDMETHOD(None, "IAGetPrimitiveTopology"), 181 | comtypes.STDMETHOD(None, "VSGetShaderResources"), 182 | comtypes.STDMETHOD(None, "VSGetSamplers"), 183 | comtypes.STDMETHOD(None, "GetPredication"), 184 | comtypes.STDMETHOD(None, "GSGetShaderResources"), 185 | comtypes.STDMETHOD(None, "GSGetSamplers"), 186 | comtypes.STDMETHOD(None, "OMGetRenderTargets"), 187 | comtypes.STDMETHOD(None, "OMGetRenderTargetsAndUnorderedAccessViews"), 188 | comtypes.STDMETHOD(None, "OMGetBlendState"), 189 | comtypes.STDMETHOD(None, "OMGetDepthStencilState"), 190 | comtypes.STDMETHOD(None, "SOGetTargets"), 191 | comtypes.STDMETHOD(None, "RSGetState"), 192 | comtypes.STDMETHOD(None, "RSGetViewports"), 193 | comtypes.STDMETHOD(None, "RSGetScissorRects"), 194 | comtypes.STDMETHOD(None, "HSGetShaderResources"), 195 | comtypes.STDMETHOD(None, "HSGetShader"), 196 | comtypes.STDMETHOD(None, "HSGetSamplers"), 197 | comtypes.STDMETHOD(None, "HSGetConstantBuffers"), 198 | comtypes.STDMETHOD(None, "DSGetShaderResources"), 199 | comtypes.STDMETHOD(None, "DSGetShader"), 200 | comtypes.STDMETHOD(None, "DSGetSamplers"), 201 | comtypes.STDMETHOD(None, "DSGetConstantBuffers"), 202 | comtypes.STDMETHOD(None, "CSGetShaderResources"), 203 | comtypes.STDMETHOD(None, "CSGetUnorderedAccessViews"), 204 | comtypes.STDMETHOD(None, "CSGetShader"), 205 | comtypes.STDMETHOD(None, "CSGetSamplers"), 206 | comtypes.STDMETHOD(None, "CSGetConstantBuffers"), 207 | comtypes.STDMETHOD(None, "ClearState"), 208 | comtypes.STDMETHOD(None, "Flush"), 209 | comtypes.STDMETHOD(None, "GetType"), 210 | comtypes.STDMETHOD(wintypes.UINT, "GetContextFlags"), 211 | comtypes.STDMETHOD(comtypes.HRESULT, "FinishCommandList"), 212 | ] 213 | 214 | 215 | class ID3D11Device(comtypes.IUnknown): 216 | _iid_ = comtypes.GUID("{db6f6ddb-ac77-4e88-8253-819df9bbf140}") 217 | _methods_ = [ 218 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateBuffer"), 219 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateTexture1D"), 220 | comtypes.STDMETHOD( 221 | comtypes.HRESULT, 222 | "CreateTexture2D", 223 | [ 224 | ctypes.POINTER(D3D11_TEXTURE2D_DESC), 225 | ctypes.POINTER(None), 226 | ctypes.POINTER(ctypes.POINTER(ID3D11Texture2D)), 227 | ], 228 | ), 229 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateTexture3D"), 230 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateShaderResourceView"), 231 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateUnorderedAccessView"), 232 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateRenderTargetView"), 233 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateDepthStencilView"), 234 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateInputLayout"), 235 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateVertexShader"), 236 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateGeometryShader"), 237 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateGeometryShaderWithStreamOutput"), 238 | comtypes.STDMETHOD(comtypes.HRESULT, "CreatePixelShader"), 239 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateHullShader"), 240 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateDomainShader"), 241 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateComputeShader"), 242 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateClassLinkage"), 243 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateBlendState"), 244 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateDepthStencilState"), 245 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateRasterizerState"), 246 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateSamplerState"), 247 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateQuery"), 248 | comtypes.STDMETHOD(comtypes.HRESULT, "CreatePredicate"), 249 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateCounter"), 250 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateDeferredContext"), 251 | comtypes.STDMETHOD(comtypes.HRESULT, "OpenSharedResource"), 252 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckFormatSupport"), 253 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckMultisampleQualityLevels"), 254 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckCounterInfo"), 255 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckCounter"), 256 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckFeatureSupport"), 257 | comtypes.STDMETHOD(comtypes.HRESULT, "GetPrivateData"), 258 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateData"), 259 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateDataInterface"), 260 | comtypes.STDMETHOD(ctypes.c_int32, "GetFeatureLevel"), 261 | comtypes.STDMETHOD(ctypes.c_uint, "GetCreationFlags"), 262 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDeviceRemovedReason"), 263 | comtypes.STDMETHOD( 264 | None, 265 | "GetImmediateContext", 266 | [ctypes.POINTER(ctypes.POINTER(ID3D11DeviceContext))], 267 | ), 268 | comtypes.STDMETHOD(comtypes.HRESULT, "SetExceptionMode"), 269 | comtypes.STDMETHOD(ctypes.c_uint, "GetExceptionMode"), 270 | ] 271 | -------------------------------------------------------------------------------- /bettercam/_libs/dxgi.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import ctypes.wintypes as wintypes 3 | import comtypes 4 | from .d3d11 import ID3D11Device 5 | 6 | 7 | DXGI_ERROR_ACCESS_LOST = 0x887A0026 8 | DXGI_ERROR_NOT_FOUND = 0x887A0002 9 | DXGI_ERROR_WAIT_TIMEOUT = 0x887A0027 10 | 11 | 12 | class LUID(ctypes.Structure): 13 | _fields_ = [("LowPart", wintypes.DWORD), ("HighPart", wintypes.LONG)] 14 | 15 | 16 | class DXGI_ADAPTER_DESC1(ctypes.Structure): 17 | _fields_ = [ 18 | ("Description", wintypes.WCHAR * 128), 19 | ("VendorId", wintypes.UINT), 20 | ("DeviceId", wintypes.UINT), 21 | ("SubSysId", wintypes.UINT), 22 | ("Revision", wintypes.UINT), 23 | ("DedicatedVideoMemory", wintypes.ULARGE_INTEGER), 24 | ("DedicatedSystemMemory", wintypes.ULARGE_INTEGER), 25 | ("SharedSystemMemory", wintypes.ULARGE_INTEGER), 26 | ("AdapterLuid", LUID), 27 | ("Flags", wintypes.UINT), 28 | ] 29 | 30 | 31 | class DXGI_OUTPUT_DESC(ctypes.Structure): 32 | _fields_ = [ 33 | ("DeviceName", wintypes.WCHAR * 32), 34 | ("DesktopCoordinates", wintypes.RECT), 35 | ("AttachedToDesktop", wintypes.BOOL), 36 | ("Rotation", wintypes.UINT), 37 | ("Monitor", wintypes.HMONITOR), 38 | ] 39 | 40 | 41 | class DXGI_OUTDUPL_POINTER_POSITION(ctypes.Structure): 42 | _fields_ = [("Position", wintypes.POINT), ("Visible", wintypes.BOOL)] 43 | 44 | 45 | class DXGI_OUTDUPL_FRAME_INFO(ctypes.Structure): 46 | _fields_ = [ 47 | ("LastPresentTime", wintypes.LARGE_INTEGER), 48 | ("LastMouseUpdateTime", wintypes.LARGE_INTEGER), 49 | ("AccumulatedFrames", wintypes.UINT), 50 | ("RectsCoalesced", wintypes.BOOL), 51 | ("ProtectedContentMaskedOut", wintypes.BOOL), 52 | ("PointerPosition", DXGI_OUTDUPL_POINTER_POSITION), 53 | ("TotalMetadataBufferSize", wintypes.UINT), 54 | ("PointerShapeBufferSize", wintypes.UINT), 55 | ] 56 | 57 | 58 | class DXGI_MAPPED_RECT(ctypes.Structure): 59 | _fields_ = [("Pitch", wintypes.INT), ("pBits", ctypes.POINTER(wintypes.FLOAT))] 60 | 61 | 62 | class IDXGIObject(comtypes.IUnknown): 63 | _iid_ = comtypes.GUID("{aec22fb8-76f3-4639-9be0-28eb43a67a2e}") 64 | _methods_ = [ 65 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateData"), 66 | comtypes.STDMETHOD(comtypes.HRESULT, "SetPrivateDataInterface"), 67 | comtypes.STDMETHOD(comtypes.HRESULT, "GetPrivateData"), 68 | comtypes.STDMETHOD(comtypes.HRESULT, "GetParent"), 69 | ] 70 | 71 | 72 | class IDXGIDeviceSubObject(IDXGIObject): 73 | _iid_ = comtypes.GUID("{3d3e0379-f9de-4d58-bb6c-18d62992f1a6}") 74 | _methods_ = [ 75 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDevice"), 76 | ] 77 | 78 | 79 | class IDXGIResource(IDXGIDeviceSubObject): 80 | _iid_ = comtypes.GUID("{035f3ab4-482e-4e50-b41f-8a7f8bd8960b}") 81 | _methods_ = [ 82 | comtypes.STDMETHOD(comtypes.HRESULT, "GetSharedHandle"), 83 | comtypes.STDMETHOD(comtypes.HRESULT, "GetUsage"), 84 | comtypes.STDMETHOD(comtypes.HRESULT, "SetEvictionPriority"), 85 | comtypes.STDMETHOD(comtypes.HRESULT, "GetEvictionPriority"), 86 | ] 87 | 88 | 89 | class IDXGISurface(IDXGIDeviceSubObject): 90 | _iid_ = comtypes.GUID("{cafcb56c-6ac3-4889-bf47-9e23bbd260ec}") 91 | _methods_ = [ 92 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDesc"), 93 | comtypes.STDMETHOD( 94 | comtypes.HRESULT, "Map", [ctypes.POINTER(DXGI_MAPPED_RECT), wintypes.UINT] 95 | ), 96 | comtypes.STDMETHOD(comtypes.HRESULT, "Unmap"), 97 | ] 98 | 99 | 100 | class IDXGIOutputDuplication(IDXGIObject): 101 | _iid_ = comtypes.GUID("{191cfac3-a341-470d-b26e-a864f428319c}") 102 | _methods_ = [ 103 | comtypes.STDMETHOD(None, "GetDesc"), 104 | comtypes.STDMETHOD( 105 | comtypes.HRESULT, 106 | "AcquireNextFrame", 107 | [ 108 | wintypes.UINT, 109 | ctypes.POINTER(DXGI_OUTDUPL_FRAME_INFO), 110 | ctypes.POINTER(ctypes.POINTER(IDXGIResource)), 111 | ], 112 | ), 113 | comtypes.STDMETHOD(comtypes.HRESULT, "GetFrameDirtyRects"), 114 | comtypes.STDMETHOD(comtypes.HRESULT, "GetFrameMoveRects"), 115 | comtypes.STDMETHOD(comtypes.HRESULT, "GetFramePointerShape"), 116 | comtypes.STDMETHOD(comtypes.HRESULT, "MapDesktopSurface"), 117 | comtypes.STDMETHOD(comtypes.HRESULT, "UnMapDesktopSurface"), 118 | comtypes.STDMETHOD(comtypes.HRESULT, "ReleaseFrame"), 119 | ] 120 | 121 | 122 | class IDXGIOutput(IDXGIObject): 123 | _iid_ = comtypes.GUID("{ae02eedb-c735-4690-8d52-5a8dc20213aa}") 124 | _methods_ = [ 125 | comtypes.STDMETHOD( 126 | comtypes.HRESULT, "GetDesc", [ctypes.POINTER(DXGI_OUTPUT_DESC)] 127 | ), 128 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDisplayModeList"), 129 | comtypes.STDMETHOD(comtypes.HRESULT, "FindClosestMatchingMode"), 130 | comtypes.STDMETHOD(comtypes.HRESULT, "WaitForVBlank"), 131 | comtypes.STDMETHOD(comtypes.HRESULT, "TakeOwnership"), 132 | comtypes.STDMETHOD(None, "ReleaseOwnership"), 133 | comtypes.STDMETHOD(comtypes.HRESULT, "GetGammaControlCapabilities"), 134 | comtypes.STDMETHOD(comtypes.HRESULT, "SetGammaControl"), 135 | comtypes.STDMETHOD(comtypes.HRESULT, "GetGammaControl"), 136 | comtypes.STDMETHOD(comtypes.HRESULT, "SetDisplaySurface"), 137 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDisplaySurfaceData"), 138 | comtypes.STDMETHOD(comtypes.HRESULT, "GetFrameStatistics"), 139 | ] 140 | 141 | 142 | class IDXGIOutput1(IDXGIOutput): 143 | _iid_ = comtypes.GUID("{00cddea8-939b-4b83-a340-a685226666cc}") 144 | _methods_ = [ 145 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDisplayModeList1"), 146 | comtypes.STDMETHOD(comtypes.HRESULT, "FindClosestMatchingMode1"), 147 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDisplaySurfaceData1"), 148 | comtypes.STDMETHOD( 149 | comtypes.HRESULT, 150 | "DuplicateOutput", 151 | [ 152 | ctypes.POINTER(ID3D11Device), 153 | ctypes.POINTER(ctypes.POINTER(IDXGIOutputDuplication)), 154 | ], 155 | ), 156 | ] 157 | 158 | 159 | class IDXGIAdapter(IDXGIObject): 160 | _iid_ = comtypes.GUID("{2411e7e1-12ac-4ccf-bd14-9798e8534dc0}") 161 | _methods_ = [ 162 | comtypes.STDMETHOD( 163 | comtypes.HRESULT, 164 | "EnumOutputs", 165 | [wintypes.UINT, ctypes.POINTER(ctypes.POINTER(IDXGIOutput))], 166 | ), 167 | comtypes.STDMETHOD(comtypes.HRESULT, "GetDesc"), 168 | comtypes.STDMETHOD(comtypes.HRESULT, "CheckInterfaceSupport"), 169 | ] 170 | 171 | 172 | class IDXGIAdapter1(IDXGIAdapter): 173 | _iid_ = comtypes.GUID("{29038f61-3839-4626-91fd-086879011a05}") 174 | _methods_ = [ 175 | comtypes.STDMETHOD( 176 | comtypes.HRESULT, "GetDesc1", [ctypes.POINTER(DXGI_ADAPTER_DESC1)] 177 | ), 178 | ] 179 | 180 | 181 | class IDXGIFactory(IDXGIObject): 182 | _iid_ = comtypes.GUID("{7b7166ec-21c7-44ae-b21a-c9ae321ae369}") 183 | _methods_ = [ 184 | comtypes.STDMETHOD(comtypes.HRESULT, "EnumAdapters"), 185 | comtypes.STDMETHOD(comtypes.HRESULT, "MakeWindowAssociation"), 186 | comtypes.STDMETHOD(comtypes.HRESULT, "GetWindowAssociation"), 187 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateSwapChain"), 188 | comtypes.STDMETHOD(comtypes.HRESULT, "CreateSoftwareAdapter"), 189 | ] 190 | 191 | 192 | class IDXGIFactory1(IDXGIFactory): 193 | _iid_ = comtypes.GUID("{770aae78-f26f-4dba-a829-253c83d1b387}") 194 | _methods_ = [ 195 | comtypes.STDMETHOD( 196 | comtypes.HRESULT, 197 | "EnumAdapters1", 198 | [ctypes.c_uint, ctypes.POINTER(ctypes.POINTER(IDXGIAdapter1))], 199 | ), 200 | comtypes.STDMETHOD(wintypes.BOOL, "IsCurrent"), 201 | ] 202 | -------------------------------------------------------------------------------- /bettercam/_libs/user32.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import ctypes.wintypes as wintypes 3 | 4 | 5 | MONITORINFOF_PRIMARY = 0x00000001 6 | DISPLAY_DEVICE_ACTIVE = 1 7 | DISPLAY_DEVICE_PRIMARY_DEVICE = 4 8 | 9 | 10 | class DISPLAY_DEVICE(ctypes.Structure): 11 | _fields_ = [ 12 | ("cb", wintypes.DWORD), 13 | ("DeviceName", wintypes.WCHAR * 32), 14 | ("DeviceString", wintypes.WCHAR * 128), 15 | ("StateFlags", wintypes.DWORD), 16 | ("DeviceID", wintypes.WCHAR * 128), 17 | ("DeviceKey", wintypes.WCHAR * 128), 18 | ] 19 | 20 | 21 | class MONITORINFOEXW(ctypes.Structure): 22 | _fields_ = [ 23 | ("cbSize", wintypes.DWORD), 24 | ("rcMonitor", wintypes.RECT), 25 | ("rcWork", wintypes.RECT), 26 | ("dwFlags", wintypes.DWORD), 27 | ("szDevice", wintypes.WCHAR * 32), 28 | ] 29 | -------------------------------------------------------------------------------- /bettercam/bettercam.py: -------------------------------------------------------------------------------- 1 | import time 2 | import ctypes 3 | from typing import Tuple 4 | from threading import Thread, Event, Lock 5 | import comtypes 6 | import numpy as np 7 | from bettercam.core import Device, Output, StageSurface, Duplicator 8 | from bettercam.processor import Processor 9 | from bettercam.util.timer import ( 10 | create_high_resolution_timer, 11 | set_periodic_timer, 12 | wait_for_timer, 13 | cancel_timer, 14 | INFINITE, 15 | WAIT_FAILED, 16 | ) 17 | 18 | 19 | class BetterCam: 20 | def __init__( 21 | self, 22 | output: Output, 23 | device: Device, 24 | region: Tuple[int, int, int, int], 25 | output_color: str = "RGB", 26 | nvidia_gpu: bool = False, 27 | max_buffer_len=64, 28 | ) -> None: 29 | self._output: Output = output 30 | self._device: Device = device 31 | self._stagesurf: StageSurface = StageSurface( 32 | output=self._output, device=self._device 33 | ) 34 | self._duplicator: Duplicator = Duplicator( 35 | output=self._output, device=self._device 36 | ) 37 | self.nvidia_gpu = nvidia_gpu 38 | # if nvidia_gpu: 39 | # import cupy as np 40 | self._processor: Processor = Processor(output_color=output_color, nvidia_gpu=nvidia_gpu) 41 | 42 | self.width, self.height = self._output.resolution 43 | self.channel_size = len(output_color) if output_color != "GRAY" else 1 44 | self.rotation_angle: int = self._output.rotation_angle 45 | 46 | self._region_set_by_user = region is not None 47 | self.region: Tuple[int, int, int, int] = region 48 | if self.region is None: 49 | self.region = (0, 0, self.width, self.height) 50 | self._validate_region(self.region) 51 | 52 | self.max_buffer_len = max_buffer_len 53 | self.is_capturing = False 54 | 55 | self.__thread = None 56 | self.__lock = Lock() 57 | self.__stop_capture = Event() 58 | 59 | self.__frame_available = Event() 60 | self.__frame_buffer: np.ndarray = None 61 | self.__head = 0 62 | self.__tail = 0 63 | self.__full = False 64 | 65 | self.__timer_handle = None 66 | 67 | self.__frame_count = 0 68 | self.__capture_start_time = 0 69 | 70 | def grab(self, region: Tuple[int, int, int, int] = None): 71 | if region is None: 72 | region = self.region 73 | else: 74 | self._validate_region(region) 75 | frame = self._grab(region) 76 | return frame 77 | 78 | def _grab(self, region: Tuple[int, int, int, int]): 79 | if self._duplicator.update_frame(): 80 | if not self._duplicator.updated: 81 | return None 82 | self._device.im_context.CopyResource( 83 | self._stagesurf.texture, self._duplicator.texture 84 | ) 85 | self._duplicator.release_frame() 86 | rect = self._stagesurf.map() 87 | frame = self._processor.process( 88 | rect, self.width, self.height, region, self.rotation_angle 89 | ) 90 | self._stagesurf.unmap() 91 | return frame 92 | else: 93 | self._on_output_change() 94 | return None 95 | 96 | def _on_output_change(self): 97 | time.sleep(0.1) # Wait for Display mode change (Access Lost) 98 | self._duplicator.release() 99 | self._stagesurf.release() 100 | self._output.update_desc() 101 | self.width, self.height = self._output.resolution 102 | if self.region is None or not self._region_set_by_user: 103 | self.region = (0, 0, self.width, self.height) 104 | self._validate_region(self.region) 105 | if self.is_capturing: 106 | self._rebuild_frame_buffer(self.region) 107 | self.rotation_angle = self._output.rotation_angle 108 | while True: 109 | try: 110 | self._stagesurf.rebuild(output=self._output, device=self._device) 111 | self._duplicator = Duplicator(output=self._output, device=self._device) 112 | except comtypes.COMError as ce: 113 | continue 114 | break 115 | 116 | def start( 117 | self, 118 | region: Tuple[int, int, int, int] = None, 119 | target_fps: int = 60, 120 | video_mode=False, 121 | delay: int = 0, 122 | ): 123 | if delay != 0: 124 | time.sleep(delay) 125 | self._on_output_change() 126 | if region is None: 127 | region = self.region 128 | self._validate_region(region) 129 | self.is_capturing = True 130 | frame_shape = (region[3] - region[1], region[2] - region[0], self.channel_size) 131 | self.__frame_buffer = np.ndarray( 132 | (self.max_buffer_len, *frame_shape), dtype=np.uint8 133 | ) 134 | self.__thread = Thread( 135 | target=self.__capture, 136 | name="BetterCam", 137 | args=(region, target_fps, video_mode), 138 | ) 139 | self.__thread.daemon = True 140 | self.__thread.start() 141 | 142 | def stop(self): 143 | if self.is_capturing: 144 | self.__frame_available.set() 145 | self.__stop_capture.set() 146 | if self.__thread is not None: 147 | self.__thread.join(timeout=10) 148 | self.is_capturing = False 149 | self.__frame_buffer = None 150 | self.__frame_count = 0 151 | self.__frame_available.clear() 152 | self.__stop_capture.clear() 153 | 154 | def get_latest_frame(self): 155 | self.__frame_available.wait() 156 | with self.__lock: 157 | ret = self.__frame_buffer[(self.__head - 1) % self.max_buffer_len] 158 | self.__frame_available.clear() 159 | return np.array(ret) 160 | 161 | def __capture( 162 | self, region: Tuple[int, int, int, int], target_fps: int = 60, video_mode=False 163 | ): 164 | if target_fps != 0: 165 | period_ms = 1000 // target_fps # millisenonds for periodic timer 166 | self.__timer_handle = create_high_resolution_timer() 167 | set_periodic_timer(self.__timer_handle, period_ms) 168 | 169 | self.__capture_start_time = time.perf_counter() 170 | 171 | capture_error = None 172 | 173 | while not self.__stop_capture.is_set(): 174 | if self.__timer_handle: 175 | res = wait_for_timer(self.__timer_handle, INFINITE) 176 | if res == WAIT_FAILED: 177 | self.__stop_capture.set() 178 | capture_error = ctypes.WinError() 179 | continue 180 | try: 181 | frame = self._grab(region) 182 | if frame is not None: 183 | with self.__lock: 184 | self.__frame_buffer[self.__head] = frame 185 | if self.__full: 186 | self.__tail = (self.__tail + 1) % self.max_buffer_len 187 | self.__head = (self.__head + 1) % self.max_buffer_len 188 | self.__frame_available.set() 189 | self.__frame_count += 1 190 | self.__full = self.__head == self.__tail 191 | elif video_mode: 192 | with self.__lock: 193 | self.__frame_buffer[self.__head] = np.array( 194 | self.__frame_buffer[(self.__head - 1) % self.max_buffer_len] 195 | ) 196 | if self.__full: 197 | self.__tail = (self.__tail + 1) % self.max_buffer_len 198 | self.__head = (self.__head + 1) % self.max_buffer_len 199 | self.__frame_available.set() 200 | self.__frame_count += 1 201 | self.__full = self.__head == self.__tail 202 | except Exception as e: 203 | import traceback 204 | 205 | print(traceback.format_exc()) 206 | self.__stop_capture.set() 207 | capture_error = e 208 | continue 209 | if self.__timer_handle: 210 | cancel_timer(self.__timer_handle) 211 | self.__timer_handle = None 212 | if capture_error is not None: 213 | self.stop() 214 | raise capture_error 215 | print( 216 | f"Screen Capture FPS: {int(self.__frame_count/(time.perf_counter() - self.__capture_start_time))}" 217 | ) 218 | 219 | def _rebuild_frame_buffer(self, region: Tuple[int, int, int, int]): 220 | if region is None: 221 | region = self.region 222 | frame_shape = ( 223 | region[3] - region[1], 224 | region[2] - region[0], 225 | self.channel_size, 226 | ) 227 | with self.__lock: 228 | self.__frame_buffer = np.ndarray( 229 | (self.max_buffer_len, *frame_shape), dtype=np.uint8 230 | ) 231 | self.__head = 0 232 | self.__tail = 0 233 | self.__full = False 234 | 235 | def _validate_region(self, region: Tuple[int, int, int, int]): 236 | l, t, r, b = region 237 | if not (self.width >= r > l >= 0 and self.height >= b > t >= 0): 238 | raise ValueError( 239 | f"Invalid Region: Region should be in {self.width}x{self.height}" 240 | ) 241 | 242 | def release(self): 243 | self.stop() 244 | self._duplicator.release() 245 | self._stagesurf.release() 246 | 247 | def __del__(self): 248 | self.release() 249 | 250 | def __repr__(self) -> str: 251 | return "<{}:\n\t{},\n\t{},\n\t{},\n\t{}\n>".format( 252 | self.__class__.__name__, 253 | self._device, 254 | self._output, 255 | self._stagesurf, 256 | self._duplicator, 257 | ) -------------------------------------------------------------------------------- /bettercam/core/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["Device", "Output", "StageSurface", "Duplicator"] 2 | 3 | 4 | from bettercam.core.device import Device 5 | from bettercam.core.output import Output 6 | from bettercam.core.stagesurf import StageSurface 7 | from bettercam.core.duplicator import Duplicator 8 | -------------------------------------------------------------------------------- /bettercam/core/device.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from dataclasses import dataclass 3 | from typing import List 4 | import comtypes 5 | from bettercam._libs.d3d11 import * 6 | from bettercam._libs.dxgi import * 7 | 8 | 9 | @dataclass 10 | class Device: 11 | adapter: ctypes.POINTER(IDXGIAdapter1) 12 | device: ctypes.POINTER(ID3D11Device) = None 13 | context: ctypes.POINTER(ID3D11DeviceContext) = None 14 | im_context: ctypes.POINTER(ID3D11DeviceContext) = None 15 | desc: DXGI_ADAPTER_DESC1 = None 16 | 17 | def __post_init__(self) -> None: 18 | self.desc = DXGI_ADAPTER_DESC1() 19 | self.adapter.GetDesc1(ctypes.byref(self.desc)) 20 | 21 | D3D11CreateDevice = ctypes.windll.d3d11.D3D11CreateDevice 22 | 23 | feature_levels = [ 24 | D3D_FEATURE_LEVEL_11_0, 25 | D3D_FEATURE_LEVEL_10_1, 26 | D3D_FEATURE_LEVEL_10_0, 27 | ] 28 | 29 | self.device = ctypes.POINTER(ID3D11Device)() 30 | self.context = ctypes.POINTER(ID3D11DeviceContext)() 31 | self.im_context = ctypes.POINTER(ID3D11DeviceContext)() 32 | 33 | D3D11CreateDevice( 34 | self.adapter, 35 | 0, 36 | None, 37 | 0, 38 | ctypes.byref((ctypes.c_uint * len(feature_levels))(*feature_levels)), 39 | len(feature_levels), 40 | 7, 41 | ctypes.byref(self.device), 42 | None, 43 | ctypes.byref(self.context), 44 | ) 45 | self.device.GetImmediateContext(ctypes.byref(self.im_context)) 46 | 47 | def enum_outputs(self) -> List[ctypes.POINTER(IDXGIOutput1)]: 48 | i = 0 49 | p_outputs = [] 50 | while True: 51 | try: 52 | p_output = ctypes.POINTER(IDXGIOutput1)() 53 | self.adapter.EnumOutputs(i, ctypes.byref(p_output)) 54 | p_outputs.append(p_output) 55 | i += 1 56 | except comtypes.COMError as ce: 57 | if ctypes.c_int32(DXGI_ERROR_NOT_FOUND).value == ce.args[0]: 58 | break 59 | else: 60 | raise ce 61 | return p_outputs 62 | 63 | @property 64 | def description(self) -> str: 65 | return self.desc.Description 66 | 67 | @property 68 | def vram_size(self) -> int: 69 | return self.desc.DedicatedVideoMemory 70 | 71 | @property 72 | def vendor_id(self) -> int: 73 | return self.desc.VendorId 74 | 75 | def __repr__(self) -> str: 76 | return "<{} Name:{} Dedicated VRAM:{}Mb VendorId:{}>".format( 77 | self.__class__.__name__, 78 | self.desc.Description, 79 | self.desc.DedicatedVideoMemory // 1048576, 80 | self.desc.VendorId, 81 | ) 82 | -------------------------------------------------------------------------------- /bettercam/core/duplicator.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from dataclasses import dataclass, InitVar 3 | from bettercam._libs.d3d11 import * 4 | from bettercam._libs.dxgi import * 5 | from bettercam.core.device import Device 6 | from bettercam.core.output import Output 7 | 8 | 9 | @dataclass 10 | class Duplicator: 11 | texture: ctypes.POINTER(ID3D11Texture2D) = ctypes.POINTER(ID3D11Texture2D)() 12 | duplicator: ctypes.POINTER(IDXGIOutputDuplication) = None 13 | updated: bool = False 14 | output: InitVar[Output] = None 15 | device: InitVar[Device] = None 16 | 17 | def __post_init__(self, output: Output, device: Device) -> None: 18 | self.duplicator = ctypes.POINTER(IDXGIOutputDuplication)() 19 | output.output.DuplicateOutput(device.device, ctypes.byref(self.duplicator)) 20 | 21 | def update_frame(self): 22 | info = DXGI_OUTDUPL_FRAME_INFO() 23 | res = ctypes.POINTER(IDXGIResource)() 24 | try: 25 | self.duplicator.AcquireNextFrame( 26 | 0, 27 | ctypes.byref(info), 28 | ctypes.byref(res), 29 | ) 30 | except comtypes.COMError as ce: 31 | if ctypes.c_int32(DXGI_ERROR_ACCESS_LOST).value == ce.args[0]: 32 | return False 33 | if ctypes.c_int32(DXGI_ERROR_WAIT_TIMEOUT).value == ce.args[0]: 34 | self.updated = False 35 | return True 36 | else: 37 | raise ce 38 | try: 39 | self.texture = res.QueryInterface(ID3D11Texture2D) 40 | except comtypes.COMError as ce: 41 | self.duplicator.ReleaseFrame() 42 | self.updated = True 43 | return True 44 | 45 | def release_frame(self): 46 | self.duplicator.ReleaseFrame() 47 | 48 | def release(self): 49 | if self.duplicator is not None: 50 | self.duplicator.Release() 51 | self.duplicator = None 52 | 53 | def __repr__(self) -> str: 54 | return "<{} Initalized:{}>".format( 55 | self.__class__.__name__, 56 | self.duplicator is not None, 57 | ) 58 | -------------------------------------------------------------------------------- /bettercam/core/output.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from typing import Tuple 3 | from dataclasses import dataclass 4 | from bettercam._libs.d3d11 import * 5 | from bettercam._libs.dxgi import * 6 | 7 | 8 | @dataclass 9 | class Output: 10 | output: ctypes.POINTER(IDXGIOutput1) 11 | rotation_mapping: tuple = (0, 0, 90, 180, 270) 12 | desc: DXGI_OUTPUT_DESC = None 13 | 14 | def __post_init__(self): 15 | self.desc = DXGI_OUTPUT_DESC() 16 | self.update_desc() 17 | 18 | def update_desc(self): 19 | if self.desc is None: 20 | self.desc = DXGI_OUTPUT_DESC() 21 | self.output.GetDesc(ctypes.byref(self.desc)) 22 | 23 | @property 24 | def hmonitor(self) -> wintypes.HMONITOR: 25 | return self.desc.Monitor 26 | 27 | @property 28 | def devicename(self) -> str: 29 | return self.desc.DeviceName 30 | 31 | @property 32 | def resolution(self) -> Tuple[int, int]: 33 | return ( 34 | (self.desc.DesktopCoordinates.right - self.desc.DesktopCoordinates.left), 35 | (self.desc.DesktopCoordinates.bottom - self.desc.DesktopCoordinates.top), 36 | ) 37 | 38 | @property 39 | def surface_size(self) -> Tuple[int, int]: 40 | if self.rotation_angle in (90, 270): 41 | return self.resolution[1], self.resolution[0] 42 | else: 43 | return self.resolution 44 | 45 | @property 46 | def attached_to_desktop(self) -> bool: 47 | return bool(self.desc.AttachedToDesktop) 48 | 49 | @property 50 | def rotation_angle(self) -> int: 51 | return self.rotation_mapping[self.desc.Rotation] 52 | 53 | def __repr__(self) -> str: 54 | return "<{} Name:{} Resolution:{} Rotation:{}>".format( 55 | self.__class__.__name__, 56 | self.devicename, 57 | self.resolution, 58 | self.rotation_angle, 59 | ) 60 | -------------------------------------------------------------------------------- /bettercam/core/stagesurf.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from dataclasses import dataclass, InitVar 3 | from bettercam._libs.d3d11 import * 4 | from bettercam._libs.dxgi import * 5 | from bettercam.core.device import Device 6 | from bettercam.core.output import Output 7 | 8 | 9 | @dataclass 10 | class StageSurface: 11 | width: ctypes.c_uint32 = 0 12 | height: ctypes.c_uint32 = 0 13 | dxgi_format: ctypes.c_uint32 = DXGI_FORMAT_B8G8R8A8_UNORM 14 | desc: D3D11_TEXTURE2D_DESC = D3D11_TEXTURE2D_DESC() 15 | texture: ctypes.POINTER(ID3D11Texture2D) = None 16 | output: InitVar[Output] = None 17 | device: InitVar[Device] = None 18 | 19 | def __post_init__(self, output, device) -> None: 20 | self.rebuild(output, device) 21 | 22 | def release(self): 23 | if self.texture is not None: 24 | self.width = 0 25 | self.height = 0 26 | self.texture.Release() 27 | self.texture = None 28 | 29 | def rebuild(self, output: Output, device: Device): 30 | self.width, self.height = output.surface_size 31 | if self.texture is None: 32 | self.desc.Width = self.width 33 | self.desc.Height = self.height 34 | self.desc.Format = self.dxgi_format 35 | self.desc.MipLevels = 1 36 | self.desc.ArraySize = 1 37 | self.desc.SampleDesc.Count = 1 38 | self.desc.SampleDesc.Quality = 0 39 | self.desc.Usage = D3D11_USAGE_STAGING 40 | self.desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ 41 | self.desc.MiscFlags = 0 42 | self.desc.BindFlags = 0 43 | self.texture = ctypes.POINTER(ID3D11Texture2D)() 44 | device.device.CreateTexture2D( 45 | ctypes.byref(self.desc), 46 | None, 47 | ctypes.byref(self.texture), 48 | ) 49 | 50 | def map(self): 51 | rect: DXGI_MAPPED_RECT = DXGI_MAPPED_RECT() 52 | self.texture.QueryInterface(IDXGISurface).Map(ctypes.byref(rect), 1) 53 | return rect 54 | 55 | def unmap(self): 56 | self.texture.QueryInterface(IDXGISurface).Unmap() 57 | 58 | def __repr__(self) -> str: 59 | repr = f"{self.width}, {self.height}, {self.dxgi_format}" 60 | return repr 61 | 62 | def __repr__(self) -> str: 63 | return "<{} Initialized:{} Size:{} Format:{}>".format( 64 | self.__class__.__name__, 65 | self.texture is not None, 66 | (self.width, self.height), 67 | "DXGI_FORMAT_B8G8R8A8_UNORM", 68 | ) 69 | -------------------------------------------------------------------------------- /bettercam/processor/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import Processor 2 | -------------------------------------------------------------------------------- /bettercam/processor/base.py: -------------------------------------------------------------------------------- 1 | import enum 2 | 3 | 4 | class ProcessorBackends(enum.Enum): 5 | PIL = 0 6 | NUMPY = 1 7 | CUPY = 2 8 | 9 | 10 | class Processor: 11 | def __init__(self, backend=ProcessorBackends.NUMPY, output_color: str = "RGB", nvidia_gpu: bool = False): 12 | self.color_mode = output_color 13 | if nvidia_gpu: 14 | backend = ProcessorBackends.CUPY 15 | self.backend = self._initialize_backend(backend) 16 | 17 | def process(self, rect, width, height, region, rotation_angle): 18 | return self.backend.process(rect, width, height, region, rotation_angle) 19 | 20 | def _initialize_backend(self, backend): 21 | if backend == ProcessorBackends.NUMPY: 22 | from bettercam.processor.numpy_processor import NumpyProcessor 23 | 24 | return NumpyProcessor(self.color_mode) 25 | 26 | elif backend == ProcessorBackends.CUPY: 27 | from bettercam.processor.cupy_processor import CupyProcessor 28 | 29 | return CupyProcessor(self.color_mode) 30 | 31 | else: 32 | print(f"Unknown backend: {backend}") 33 | -------------------------------------------------------------------------------- /bettercam/processor/cupy_processor.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import cupy as cp 3 | from .base import Processor 4 | 5 | 6 | class CupyProcessor(Processor): 7 | def __init__(self, color_mode): 8 | self.cvtcolor = None 9 | self.color_mode = color_mode 10 | if self.color_mode=='BGRA': 11 | self.color_mode = None 12 | 13 | def process_cvtcolor(self, image): 14 | import cv2 15 | 16 | # only one time process 17 | if self.cvtcolor is None: 18 | color_mapping = { 19 | "RGB": cv2.COLOR_BGRA2RGB, 20 | "RGBA": cv2.COLOR_BGRA2RGBA, 21 | "BGR": cv2.COLOR_BGRA2BGR, 22 | "GRAY": cv2.COLOR_BGRA2GRAY 23 | } 24 | cv2_code = color_mapping[self.color_mode] 25 | if cv2_code != cv2.COLOR_BGRA2GRAY: 26 | self.cvtcolor = lambda image: cv2.cvtColor(image, cv2_code) 27 | else: 28 | self.cvtcolor = lambda image: cv2.cvtColor(image, cv2_code)[ 29 | ..., cp.newaxis 30 | ] 31 | return self.cvtcolor(image) 32 | 33 | def process(self, rect, width, height, region, rotation_angle): 34 | pitch = int(rect.Pitch) 35 | 36 | if rotation_angle in (0, 180): 37 | offset = (region[1] if rotation_angle==0 else height-region[3])*pitch 38 | height = region[3] - region[1] 39 | else: 40 | offset = (region[0] if rotation_angle==270 else width-region[2])*pitch 41 | width = region[2] - region[0] 42 | 43 | if rotation_angle in (0, 180): 44 | size = pitch * height 45 | else: 46 | size = pitch * width 47 | 48 | buffer = (ctypes.c_char*size).from_address(ctypes.addressof(rect.pBits.contents)+offset)#Pointer arithmetic 49 | pitch = pitch // 4 50 | if rotation_angle in (0, 180): 51 | image = cp.frombuffer(buffer, dtype=cp.uint8).reshape(height, pitch, 4) 52 | 53 | elif rotation_angle in (90, 270): 54 | image = cp.frombuffer(buffer, dtype=cp.uint8).reshape(width, pitch, 4) 55 | 56 | if not self.color_mode is None: 57 | image = self.process_cvtcolor(image) 58 | 59 | if rotation_angle == 90: 60 | image = cp.rot90(image, axes=(1, 0)) 61 | elif rotation_angle == 180: 62 | image = cp.rot90(image, k=2, axes=(0, 1)) 63 | elif rotation_angle == 270: 64 | image = cp.rot90(image, axes=(0, 1)) 65 | 66 | if rotation_angle in (0, 180) and pitch != width: 67 | image = image[:, :width, :] 68 | elif rotation_angle in (90, 270) and pitch != height: 69 | image = image[:height, :, :] 70 | 71 | if region[3] - region[1] != image.shape[0]: 72 | image = image[region[1] : region[3], :, :] 73 | if region[2] - region[0] != image.shape[1]: 74 | image = image[:, region[0] : region[2], :] 75 | 76 | return image -------------------------------------------------------------------------------- /bettercam/processor/numpy_processor.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import numpy as np 3 | from numpy import rot90, ndarray, newaxis, uint8, zeros 4 | from numpy.ctypeslib import as_array 5 | from .base import Processor 6 | 7 | 8 | class NumpyProcessor(Processor): 9 | def __init__(self, color_mode): 10 | self.cvtcolor = None 11 | self.color_mode = color_mode 12 | self.PBYTE = ctypes.POINTER(ctypes.c_ubyte) 13 | if self.color_mode=='BGRA': 14 | self.color_mode = None 15 | 16 | def process_cvtcolor(self, image): 17 | import cv2 18 | 19 | # only one time process 20 | if self.cvtcolor is None: 21 | color_mapping = { 22 | "RGB": cv2.COLOR_BGRA2RGB, 23 | "RGBA": cv2.COLOR_BGRA2RGBA, 24 | "BGR": cv2.COLOR_BGRA2BGR, 25 | "GRAY": cv2.COLOR_BGRA2GRAY 26 | } 27 | cv2_code = color_mapping[self.color_mode] 28 | if cv2_code != cv2.COLOR_BGRA2GRAY: 29 | self.cvtcolor = lambda image: cv2.cvtColor(image, cv2_code) 30 | else: 31 | self.cvtcolor = lambda image: cv2.cvtColor(image, cv2_code)[ 32 | ..., np.newaxis 33 | ] 34 | return self.cvtcolor(image) 35 | 36 | def shot(self, image_ptr, rect, width, height): 37 | ctypes.memmove(image_ptr, rect.pBits, height*width*4) 38 | 39 | def process(self, rect, width, height, region, rotation_angle): 40 | pitch = int(rect.Pitch) 41 | 42 | if rotation_angle in (0, 180): 43 | offset = (region[1] if rotation_angle==0 else height-region[3])*pitch 44 | height = region[3] - region[1] 45 | else: 46 | offset = (region[0] if rotation_angle==270 else width-region[2])*pitch 47 | width = region[2] - region[0] 48 | 49 | if rotation_angle in (0, 180): 50 | size = pitch * height 51 | else: 52 | size = pitch * width 53 | 54 | buffer = (ctypes.c_char*size).from_address(ctypes.addressof(rect.pBits.contents)+offset)#Pointer arithmetic 55 | pitch = pitch // 4 56 | if rotation_angle in (0, 180): 57 | image = np.ndarray((height, pitch, 4), dtype=np.uint8, buffer=buffer) 58 | elif rotation_angle in (90, 270): 59 | image = np.ndarray((width, pitch, 4), dtype=np.uint8, buffer=buffer) 60 | 61 | if not self.color_mode is None: 62 | image = self.process_cvtcolor(image) 63 | 64 | if rotation_angle == 90: 65 | image = np.rot90(image, axes=(1, 0)) 66 | elif rotation_angle == 180: 67 | image = np.rot90(image, k=2, axes=(0, 1)) 68 | elif rotation_angle == 270: 69 | image = np.rot90(image, axes=(0, 1)) 70 | 71 | if rotation_angle in (0, 180) and pitch != width: 72 | image = image[:, :width, :] 73 | elif rotation_angle in (90, 270) and pitch != height: 74 | image = image[:height, :, :] 75 | 76 | if region[3] - region[1] != image.shape[0]: 77 | image = image[region[1] : region[3], :, :] 78 | if region[2] - region[0] != image.shape[1]: 79 | image = image[:, region[0] : region[2], :] 80 | 81 | return image -------------------------------------------------------------------------------- /bettercam/util/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RootKit-Org/BetterCam/b4d6b0e7dbcea58f85eb61f3324268749142d53e/bettercam/util/__init__.py -------------------------------------------------------------------------------- /bettercam/util/io.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from typing import List 3 | from collections import defaultdict 4 | import comtypes 5 | from bettercam._libs.dxgi import ( 6 | IDXGIFactory1, 7 | IDXGIAdapter1, 8 | IDXGIOutput1, 9 | DXGI_ERROR_NOT_FOUND, 10 | ) 11 | from bettercam._libs.user32 import ( 12 | DISPLAY_DEVICE, 13 | MONITORINFOEXW, 14 | DISPLAY_DEVICE_ACTIVE, 15 | DISPLAY_DEVICE_PRIMARY_DEVICE, 16 | ) 17 | 18 | 19 | def enum_dxgi_adapters() -> List[ctypes.POINTER(IDXGIAdapter1)]: 20 | create_dxgi_factory = ctypes.windll.dxgi.CreateDXGIFactory1 21 | create_dxgi_factory.argtypes = (comtypes.GUID, ctypes.POINTER(ctypes.c_void_p)) 22 | create_dxgi_factory.restype = ctypes.c_int32 23 | pfactory = ctypes.c_void_p(0) 24 | create_dxgi_factory(IDXGIFactory1._iid_, ctypes.byref(pfactory)) 25 | dxgi_factory = ctypes.POINTER(IDXGIFactory1)(pfactory.value) 26 | i = 0 27 | p_adapters = list() 28 | while True: 29 | try: 30 | p_adapter = ctypes.POINTER(IDXGIAdapter1)() 31 | dxgi_factory.EnumAdapters1(i, ctypes.byref(p_adapter)) 32 | p_adapters.append(p_adapter) 33 | i += 1 34 | except comtypes.COMError as ce: 35 | if ctypes.c_int32(DXGI_ERROR_NOT_FOUND).value == ce.args[0]: 36 | break 37 | else: 38 | raise ce 39 | return p_adapters 40 | 41 | 42 | def enum_dxgi_outputs( 43 | dxgi_adapter: ctypes.POINTER(IDXGIAdapter1), 44 | ) -> List[ctypes.POINTER(IDXGIOutput1)]: 45 | i = 0 46 | p_outputs = list() 47 | while True: 48 | try: 49 | p_output = ctypes.POINTER(IDXGIOutput1)() 50 | dxgi_adapter.EnumOutputs(i, ctypes.byref(p_output)) 51 | p_outputs.append(p_output) 52 | i += 1 53 | except comtypes.COMError as ce: 54 | if ctypes.c_int32(DXGI_ERROR_NOT_FOUND).value == ce.args[0]: 55 | break 56 | else: 57 | raise ce 58 | return p_outputs 59 | 60 | 61 | def get_output_metadata(): 62 | mapping_adapter = defaultdict(list) 63 | adapter = DISPLAY_DEVICE() 64 | adapter.cb = ctypes.sizeof(adapter) 65 | i = 0 66 | # Enumerate all adapters 67 | while ctypes.windll.user32.EnumDisplayDevicesW(0, i, ctypes.byref(adapter), 1): 68 | if adapter.StateFlags & DISPLAY_DEVICE_ACTIVE != 0: 69 | is_primary = bool(adapter.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) 70 | mapping_adapter[adapter.DeviceName] = [adapter.DeviceString, is_primary, []] 71 | display = DISPLAY_DEVICE() 72 | display.cb = ctypes.sizeof(adapter) 73 | j = 0 74 | # Enumerate Monitors 75 | while ctypes.windll.user32.EnumDisplayDevicesW( 76 | adapter.DeviceName, j, ctypes.byref(display), 0 77 | ): 78 | mapping_adapter[adapter.DeviceName][2].append( 79 | ( 80 | display.DeviceName, 81 | display.DeviceString, 82 | ) 83 | ) 84 | j += 1 85 | i += 1 86 | return mapping_adapter 87 | 88 | 89 | def get_monitor_name_by_handle(hmonitor): 90 | info = MONITORINFOEXW() 91 | info.cbSize = ctypes.sizeof(MONITORINFOEXW) 92 | if ctypes.windll.user32.GetMonitorInfoW(hmonitor, ctypes.byref(info)): 93 | return info 94 | return None 95 | -------------------------------------------------------------------------------- /bettercam/util/timer.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | from ctypes.wintypes import LARGE_INTEGER 3 | 4 | 5 | INFINITE = 0xFFFFFFFF 6 | WAIT_FAILED = 0xFFFFFFFF 7 | CREATE_WAITABLE_TIMER_HIGH_RESOLUTION = 0x00000002 8 | TIMER_MODIFY_STATE = 0x0002 9 | TIMER_ALL_ACCESS = 0x1F0003 10 | 11 | 12 | __kernel32 = ctypes.windll.kernel32 13 | 14 | 15 | def create_high_resolution_timer(): 16 | handle = __kernel32.CreateWaitableTimerExW( 17 | None, None, CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, TIMER_ALL_ACCESS 18 | ) 19 | if handle == 0: 20 | raise ctypes.WinError() 21 | return handle 22 | 23 | 24 | def set_periodic_timer(handle, period: int): 25 | res = __kernel32.SetWaitableTimer( 26 | handle, 27 | ctypes.byref(LARGE_INTEGER(0)), 28 | period, 29 | None, 30 | None, 31 | 0, 32 | ) 33 | if res == 0: 34 | raise ctypes.WinError() 35 | return True 36 | 37 | 38 | wait_for_timer = __kernel32.WaitForSingleObject 39 | cancel_timer = __kernel32.CancelWaitableTimer 40 | -------------------------------------------------------------------------------- /examples/capture_to_video.py: -------------------------------------------------------------------------------- 1 | import bettercam 2 | 3 | # install OpenCV using `pip install bettercam[cv2]` command. 4 | import cv2 5 | 6 | TOP = 0 7 | LEFT = 0 8 | RIGHT = 1920 9 | BOTTOM = 1080 10 | region = (LEFT, TOP, RIGHT, BOTTOM) 11 | title = "[BetterCam] Capture benchmark" 12 | 13 | target_fps = 30 14 | camera = bettercam.create(output_idx=0, output_color="BGR") 15 | camera.start(target_fps=target_fps, video_mode=True) 16 | writer = cv2.VideoWriter( 17 | "video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), target_fps, (1920, 1080) 18 | ) 19 | for i in range(600): 20 | writer.write(camera.get_latest_frame()) 21 | camera.stop() 22 | writer.release() 23 | -------------------------------------------------------------------------------- /examples/instant_replay.py: -------------------------------------------------------------------------------- 1 | """A Minimal example of creating a ghetto instant replay with hotkeys. 2 | Took less than 5 minutes to write using pyav + bettercam + pynput. 3 | The code is shit but you got the idea. 4 | """ 5 | from collections import deque 6 | from threading import Event, Lock 7 | import bettercam 8 | import av 9 | from pynput import keyboard 10 | 11 | 12 | stop_event = Event() 13 | buffer_lock = Lock() 14 | replay_count = 0 15 | target_fps = 120 16 | buffer = deque(maxlen=target_fps * 10) 17 | 18 | container = av.open(f"replay{replay_count}.mp4", mode="w") 19 | stream = container.add_stream("mpeg4", rate=target_fps) 20 | stream.pix_fmt, stream.height, stream.width = "yuv420p", 1080, 1920 21 | stream.bit_rate = 8_000_000 22 | 23 | camera = bettercam.create(output_color="RGB") 24 | camera.start(target_fps=target_fps, video_mode=True) 25 | 26 | 27 | def save_replay(): 28 | global container, buffer_lock, stream, buffer, replay_count 29 | print("Saving Instant Replay for the last 10 seconds...") 30 | with buffer_lock: 31 | for idx, packet in enumerate(buffer): 32 | packet.pts = packet.dts = idx 33 | container.mux(packet) 34 | for packet in stream.encode(): 35 | container.mux(packet) 36 | container.close() 37 | replay_count += 1 38 | container = av.open(f"replay{replay_count}.mp4", mode="w") 39 | stream = container.add_stream("mpeg4", rate=target_fps) 40 | stream.pix_fmt, stream.height, stream.width = "yuv420p", 1080, 1920 41 | stream.bit_rate = 8_000_000 42 | 43 | 44 | def stop_record(): 45 | global stop_event 46 | print("Closing") 47 | stop_event.set() 48 | 49 | 50 | listener = keyboard.GlobalHotKeys( 51 | {"++h": save_replay, "++i": stop_record} 52 | ) 53 | listener.start() 54 | try: 55 | listener.wait() 56 | while not stop_event.is_set(): 57 | frame = av.VideoFrame.from_ndarray(camera.get_latest_frame(), format="rgb24") 58 | try: 59 | with buffer_lock: 60 | for packet in stream.encode(frame): 61 | buffer.append(packet) 62 | del frame 63 | except Exception as e: 64 | continue 65 | finally: 66 | listener.stop() 67 | listener.join() 68 | camera.stop() 69 | container.close() 70 | -------------------------------------------------------------------------------- /images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RootKit-Org/BetterCam/b4d6b0e7dbcea58f85eb61f3324268749142d53e/images/banner.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=42"] 3 | build-backend = "setuptools.build_meta" -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = bettercam 3 | version = 0.1.1 4 | 5 | author = qfc9 6 | description = A Python high-performance screenshot library for Windows use Desktop Duplication API 7 | long_description = file: README.md 8 | long_description_content_type = text/markdown 9 | url = https://github.com/RootKit-Org/BetterCam 10 | project_urls = 11 | Source = https://github.com/RootKit-Org/BetterCam 12 | Tracker = https://github.com/RootKit-Org/BetterCam/issues 13 | keywords = screen, screenshot, screencapture, screengrab, windows 14 | license = MIT 15 | license_files = 16 | LICENSE 17 | classifiers = 18 | Development Status :: 2 - Pre-Alpha 19 | Intended Audience :: Developers 20 | Programming Language :: Python :: 3 21 | Programming Language :: Python :: 3 :: Only 22 | License :: OSI Approved :: MIT License 23 | Operating System :: Microsoft :: Windows 24 | Operating System :: Microsoft :: Windows :: Windows 8.1 25 | Operating System :: Microsoft :: Windows :: Windows 10 26 | Operating System :: Microsoft :: Windows :: Windows 11 27 | Topic :: Multimedia :: Graphics 28 | Topic :: Multimedia :: Graphics :: Capture 29 | Topic :: Multimedia :: Graphics :: Capture :: Screen Capture 30 | 31 | [options] 32 | packages = find: 33 | python_requires = >=3.8 34 | install_requires = 35 | numpy 36 | comtypes 37 | [options.extras_require] 38 | cv2 = opencv-python 39 | [options.packages.find] 40 | include = bettercam* -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | with open("README.md", "r", encoding='utf-8') as f: 4 | long_description = f.read() 5 | 6 | setup( 7 | name="bettercam", 8 | version="1.0.0", 9 | description = "A Python high-performance screenshot library for Windows use Desktop Duplication API", 10 | packages=find_packages(where="find:"), 11 | long_description=long_description, 12 | long_description_content_type="text/markdown", 13 | url="https://github.com/RootKit-Org/BetterCam", 14 | author="Qfc9", 15 | author_email="eharmon@rootkit.org", 16 | license="MIT", 17 | classifiers=[ 18 | "Development Status :: 4 - Beta", 19 | "Intended Audience :: Developers", 20 | "Programming Language :: Python :: 3", 21 | "Programming Language :: Python :: 3 :: Only", 22 | "License :: OSI Approved :: MIT License", 23 | "Operating System :: Microsoft :: Windows", 24 | "Operating System :: Microsoft :: Windows :: Windows 8.1", 25 | "Operating System :: Microsoft :: Windows :: Windows 10", 26 | "Operating System :: Microsoft :: Windows :: Windows 11", 27 | "Topic :: Multimedia :: Graphics", 28 | "Topic :: Multimedia :: Graphics :: Capture", 29 | "Topic :: Multimedia :: Graphics :: Capture :: Screen Capture" 30 | ], 31 | install_requires=["numpy", "comtypes"], 32 | extras_require={ 33 | "cv2": ["opencv-python"], 34 | }, 35 | python_requires=">=3.8", 36 | include_dirs=["bettercam"], 37 | ) --------------------------------------------------------------------------------