### Install DXcam Source: https://context7.com/ra1nty/dxcam/llms.txt Install DXcam with minimal dependencies or with full features including OpenCV and WinRT backend. ```bash # Minimal (numpy-only post-processing, DXGI backend) pip install dxcam # Full-featured: OpenCV color conversion + WinRT backend pip install "dxcam[cv2,winrt]" ``` -------------------------------- ### Install Optional Dependencies for Backends Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Install optional dependencies for OpenCV or WinRT capture backends using 'uv sync --extra'. ```bash # OpenCV processor backend support uv sync --extra cv2 # WinRT capture backend support uv sync --extra winrt ``` -------------------------------- ### Install Optional Cython Tooling Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Install optional Cython tooling using 'uv sync --extra cython'. ```bash # Optional Cython tooling uv sync --extra cython ``` -------------------------------- ### Create Virtual Environment and Install Dependencies Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Use 'uv' to create a Python 3.11 virtual environment and install development dependencies. ```bash uv venv --python 3.11 .venv uv sync --dev ``` -------------------------------- ### Install DXcam with Pip Source: https://github.com/ra1nty/dxcam/blob/main/README.md Installs the minimal DXcam package. For full features including OpenCV color conversion and WinRT capture, use the extended install command. ```bash pip install dxcam ``` ```bash pip install "dxcam[cv2,winrt]" ``` -------------------------------- ### Enumerate Devices and Outputs Source: https://context7.com/ra1nty/dxcam/llms.txt Use dxcam.device_info() and dxcam.output_info() to get details about available DXGI adapters and their connected monitors. ```python import dxcam print(dxcam.device_info()) # Device[0]: print(dxcam.output_info()) # Device[0] Output[0]: Res:(1920, 1080) Rot:0 Primary:True # Device[0] Output[1]: Res:(2560, 1440) Rot:0 Primary:False ``` -------------------------------- ### Start Screen Capture Source: https://github.com/ra1nty/dxcam/blob/main/README.md Starts a continuous screen capture process in a separate thread, storing frames in a ring buffer for efficient consumption. ```APIDOC ## Start Screen Capture ### Description Starts a continuous screen capture process in a separate thread, storing frames in a ring buffer for efficient consumption. ### Method `camera.start()` ### Parameters #### Keyword Arguments - **region** (tuple) - Optional - A tuple `(left, top, right, bottom)` defining the capture region. Defaults to the entire screen. - **target_fps** (int) - Optional - The desired frames per second for the capture. Defaults to 60. ``` -------------------------------- ### Build DXcam with Cython Kernels Source: https://github.com/ra1nty/dxcam/blob/main/README.md Install DXcam with Cython kernels for the 'numpy' processor backend. This is typically only needed for source installations. ```bash set DXCAM_BUILD_CYTHON=1 pip install -e .[cython] --no-build-isolation ``` -------------------------------- ### Start DXcam Capture with Target FPS Source: https://github.com/ra1nty/dxcam/blob/main/README.md Start the camera capture process, targeting a specific frames per second. The default is 60 FPS. Exceeding 120 FPS may be resource-intensive. ```python camera.start(target_fps=120) ``` -------------------------------- ### Color Modes and Processor Backends Source: https://context7.com/ra1nty/dxcam/llms.txt This example shows how to create dxcam instances with different output color modes (BGRA, GRAY) and processor backends (numpy). It highlights the flexibility in choosing capture and processing options. ```python import dxcam # BGRA — zero color-conversion overhead, no OpenCV required cam_bgra = dxcam.create(output_color="BGRA") # GRAY — single-channel luminance cam_gray = dxcam.create(output_color="GRAY") frame = cam_gray.grab() # frame.shape == (1080, 1920, 1) # numpy backend: Cython-accelerated kernels (falls back to cv2 silently) cam_np = dxcam.create(output_color="RGB", processor_backend="numpy") cam_bgra.release() cam_gray.release() cam_np.release() ``` -------------------------------- ### Build Local Cython Kernels Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Set the DXCAM_BUILD_CYTHON environment variable and perform an editable install with Cython extras to build local Cython kernels. ```bash set DXCAM_BUILD_CYTHON=1 uv pip install -e .[cython] --no-build-isolation ``` -------------------------------- ### Stop Screen Capture Source: https://github.com/ra1nty/dxcam/blob/main/README.md Stops the continuous screen capture process started by `start()`. ```APIDOC ## Stop Screen Capture ### Description Stops the continuous screen capture process started by `start()`. ### Method `camera.stop()` ``` -------------------------------- ### Create DXcam Camera with Processor Backend Source: https://github.com/ra1nty/dxcam/blob/main/README.md Initialize DXcam specifying the processor backend for post-processing tasks like rotation, cropping, and color conversion. 'cv2' is the default if OpenCV is installed, otherwise 'numpy' is used. ```python camera = dxcam.create(processor_backend="cv2") ``` ```python camera = dxcam.create(processor_backend="numpy") ``` -------------------------------- ### dxcam.output_info() Source: https://context7.com/ra1nty/dxcam/llms.txt Retrieves information about available display outputs, including their resolution, rotation, and primary status, which is useful for multi-monitor setups. ```APIDOC ## dxcam.output_info() ### Description Retrieves information about available display outputs across all detected graphics devices. This is useful for identifying which outputs can be captured from, especially in multi-monitor or multi-GPU configurations. ### Method `output_info()` ### Parameters None ### Request Example ```python import dxcam print(dxcam.output_info()) # Example Output: # Device[0] Output[0]: Res:(1920, 1080) Rot:0 Primary:True # Device[0] Output[1]: Res:(2560, 1440) Rot:0 Primary:False ``` ### Response #### Success Response (200) A list of strings, where each string describes a display output with its device index, output index, resolution, rotation, and primary status. #### Response Example ```json [ "Device[0] Output[0]: Res:(1920, 1080) Rot:0 Primary:True", "Device[0] Output[1]: Res:(2560, 1440) Rot:0 Primary:False" ] ``` ``` -------------------------------- ### Start Threaded Capture with DXCamera Source: https://context7.com/ra1nty/dxcam/llms.txt Launches a background thread for continuous frame capture. Specify capture region, target FPS, video mode, and initial delay. Use get_latest_frame() to consume frames. ```python import dxcam camera = dxcam.create(output_color="BGR", max_buffer_len=32) camera.start( region=(0, 0, 1280, 720), # Optional region; defaults to full output target_fps=120, # 0 = uncapped (busy-spin) video_mode=True, # Reuse previous frame when no new frame arrives delay=0, # Seconds to wait before starting capture ) print(camera.is_capturing) # True for i in range(300): frame = camera.get_latest_frame() # blocks until a new frame is ready # frame.shape == (720, 1280, 3) camera.stop() camera.release() ``` -------------------------------- ### DXCamera.stop() Source: https://context7.com/ra1nty/dxcam/llms.txt Signals the capture thread to exit, joins it with a timeout, and clears the frame buffer. This must be called before `start()` can be invoked again. ```APIDOC ## DXCamera.stop() ### Description Signals the capture thread to exit, joins it (with a 10-second timeout), and clears the ring buffer. This method must be called before `start()` can be called again. ### Method `stop()` ### Parameters None ### Request Example ```python import dxcam camera = dxcam.create() camera.start(target_fps=60) # ... capture frames ... camera.stop() ``` ### Response #### Success Response (200) None (operation is in-place) #### Response Example None ``` -------------------------------- ### DXcam Type Aliases for IDE Integration Source: https://context7.com/ra1nty/dxcam/llms.txt This snippet demonstrates the use of type aliases provided by dxcam for improved IDE support and type checking. It shows examples of defining variables with specific dxcam types. ```python from dxcam.types import CaptureBackend, ColorMode, Frame, ProcessorBackend, Region import numpy as np backend: CaptureBackend = "dxgi" # Literal["dxgi", "winrt"] color: ColorMode = "RGB" # Literal["RGB","RGBA","BGR","BGRA","GRAY"] p_back: ProcessorBackend = "cv2" # Literal["cv2", "numpy"] region: Region = (0, 0, 1920, 1080) # tuple[int, int, int, int] frame: Frame = np.zeros((1080, 1920, 3), dtype=np.uint8) # NDArray[uint8] ``` -------------------------------- ### Get Latest Frame View Source: https://github.com/ra1nty/dxcam/blob/main/README.md Provides a zero-copy view into the latest frame buffer, offering faster access at the cost of potential buffer overwrites. ```APIDOC ## Get Latest Frame View ### Description Provides a zero-copy view into the latest frame buffer, offering faster access at the cost of potential buffer overwrites. ### Method `camera.get_latest_frame_view()` ### Returns - **numpy.ndarray** - A zero-copy view of the latest frame. ``` -------------------------------- ### Start and Stop Continuous Screen Capture Source: https://github.com/ra1nty/dxcam/blob/main/README.md Initiates continuous screen capture for a specified region and target FPS, and stops it. The `is_capturing` attribute indicates the current state. ```python camera.start(region=(left, top, right, bottom), target_fps=60) camera.is_capturing # True # ... camera.stop() camera.is_capturing # False ``` -------------------------------- ### Get Latest Frame Source: https://github.com/ra1nty/dxcam/blob/main/README.md Retrieves the latest frame from the capture buffer. This method blocks until a frame is available. ```APIDOC ## Get Latest Frame ### Description Retrieves the latest frame from the capture buffer. This method blocks until a frame is available. ### Method `camera.get_latest_frame()` ### Parameters #### Keyword Arguments - **with_timestamp** (bool) - Optional - If True, returns the frame along with its timestamp. Defaults to False. ### Returns - **numpy.ndarray** - The latest captured frame. - **tuple** - If `with_timestamp=True`, returns `(frame, frame_timestamp)`. ``` -------------------------------- ### Stop Threaded Capture with DXCamera Source: https://context7.com/ra1nty/dxcam/llms.txt Signals the capture thread to exit and joins it. This must be called before starting capture again. It also clears the ring buffer. ```python import dxcam camera = dxcam.create() camera.start(target_fps=60) # ... capture frames ... camera.stop() print(camera.is_capturing) # False camera.release() ``` -------------------------------- ### Access Frame Timestamps with DXCamera Source: https://context7.com/ra1nty/dxcam/llms.txt Properties to get the timestamp of the most recently buffered frame. `latest_frame_time` provides seconds, while `latest_frame_ticks` gives raw hardware ticks. ```python import dxcam camera = dxcam.create(backend="dxgi") camera.start(target_fps=60) frame = camera.get_latest_frame() ts_seconds = camera.latest_frame_time # float or None raw_ticks = camera.latest_frame_ticks # int or None print(f"Frame at {ts_seconds:.4f}s (ticks={raw_ticks})") camera.stop() camera.release() ``` -------------------------------- ### Get Latest Frame with Timestamp Source: https://github.com/ra1nty/dxcam/blob/main/README.md Retrieve the most recent frame along with its timestamp in seconds. For 'dxgi' backend, the timestamp is from DXGI_OUTDUPL_FRAME_INFO.LastPresentTime. For 'winrt' backend, it's derived from WinRT SystemRelativeTime. ```python camera.start(target_fps=60) frame, ts = camera.get_latest_frame(with_timestamp=True) camera.stop() ``` -------------------------------- ### Video Mode Capture with OpenCV Source: https://github.com/ra1nty/dxcam/blob/main/README.md Capture frames in video mode, filling the buffer at target FPS and reusing the previous frame if necessary. This example demonstrates saving captured frames to a video file using OpenCV. ```python import cv2 import dxcam target_fps = 30 camera = dxcam.create(output_color="BGR") camera.start(target_fps=target_fps, video_mode=True) writer = cv2.VideoWriter( "video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), target_fps, (1920, 1080) ) for _ in range(600): writer.write(camera.get_latest_frame()) camera.stop() writer.release() ``` -------------------------------- ### Build API Documentation Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Generate the local API documentation site using 'pdoc' with Google-style docstrings, outputting to the 'site' directory. ```bash uv run pdoc -d google -o site dxcam dxcam.dxcam dxcam.types ``` -------------------------------- ### Create DXcam Camera with Specific Backend Source: https://github.com/ra1nty/dxcam/blob/main/README.md Initialize DXcam specifying the capture backend. 'dxgi' is the default and offers broad compatibility. 'winrt' is recommended if cursor rendering is needed. ```python camera = dxcam.create(backend="dxgi") ``` ```python camera = dxcam.create(backend="winrt") ``` -------------------------------- ### DXCamera.start() Source: https://context7.com/ra1nty/dxcam/llms.txt Launches a background daemon thread for continuous frame capture. Allows configuration of capture region, target FPS, video mode, and initial delay. ```APIDOC ## DXCamera.start() ### Description Launches a background daemon thread that continuously captures frames at a specified `target_fps` into a ring buffer of a defined `max_buffer_len`. Frames can be consumed using `get_latest_frame()`. ### Method `start( region: tuple = None, target_fps: int = 0, video_mode: bool = False, delay: float = 0.0 )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **region** (tuple, optional): The capture region as (left, top, right, bottom). Defaults to the full screen output. - **target_fps** (int, optional): The desired frames per second for capture. `0` means uncapped (busy-spin). Defaults to `0`. - **video_mode** (bool, optional): If `True`, reuses the previous frame when no new frame arrives. Defaults to `False`. - **delay** (float, optional): Seconds to wait before starting capture. Defaults to `0.0`. ### Request Example ```python import dxcam camera = dxcam.create(output_color="BGR", max_buffer_len=32) camera.start( region=(0, 0, 1280, 720), target_fps=120, video_mode=True, delay=0, ) ``` ### Response #### Success Response (200) None (operation is in-place) #### Response Example None ``` -------------------------------- ### Create Multiple DXcam Instances for Monitors/GPUs Source: https://github.com/ra1nty/dxcam/blob/main/README.md Demonstrates creating separate DXcam instances for different outputs on the same or different GPUs. Each instance can capture from a specific monitor or output. ```python cam1 = dxcam.create(device_idx=0, output_idx=0) cam2 = dxcam.create(device_idx=0, output_idx=1) cam3 = dxcam.create(device_idx=1, output_idx=1) img1 = cam1.grab() img2 = cam2.grab() img3 = cam3.grab() ``` -------------------------------- ### Create DXCamera Instance Source: https://context7.com/ra1nty/dxcam/llms.txt Create a DXCamera instance using default settings or specify detailed configuration for device, output, region, color format, buffer length, backend, and processor. ```python import dxcam # Default: primary output, device 0, DXGI backend, RGB output, cv2 processor camera = dxcam.create() # Full explicit configuration camera = dxcam.create( device_idx=0, # DXGI adapter index output_idx=0, # Monitor index on that adapter (None = primary) region=(0, 0, 1920, 1080), # Optional initial capture region (left, top, right, bottom) output_color="BGR", # "RGB" | "RGBA" | "BGR" | "BGRA" | "GRAY" max_buffer_len=16, # Ring-buffer depth for threaded capture backend="dxgi", # "dxgi" | "winrt" processor_backend="cv2" # "cv2" | "numpy" ) frame = camera.grab() # numpy.ndarray shape (H, W, 3), dtype=uint8, or None camera.release() ``` -------------------------------- ### Create DXcam Instance Source: https://github.com/ra1nty/dxcam/blob/main/README.md Instantiates a DXcam camera object for capturing the primary output on device 0. You can specify backend and processor backends during creation. ```python import dxcam camera = dxcam.create() # primary output on device 0 ``` ```python camera = dxcam.create( backend="dxgi", # default Desktop Duplication backend processor_backend="cv2" # default OpenCV processor ) ``` -------------------------------- ### dxcam.create() Source: https://context7.com/ra1nty/dxcam/llms.txt Creates a DXCamera instance. It acts as a factory, returning a singleton instance for a given configuration to avoid redundant resource allocation. ```APIDOC ## dxcam.create() ### Description Creates a camera instance. This factory function returns a `DXCamera` singleton per `(device_idx, output_idx, backend)` tuple. Calling `create()` multiple times with the same parameters will return the existing instance. ### Parameters * **device_idx** (int) - Optional - The index of the DXGI adapter to use. * **output_idx** (int) - Optional - The index of the monitor on the specified adapter. `None` defaults to the primary monitor. * **region** (tuple) - Optional - An initial capture region defined as `(left, top, right, bottom)`. * **output_color** (str) - Optional - The desired color format for the output frames. Supported values: `"RGB"`, `"RGBA"`, `"BGR"`, `"BGRA"`, `"GRAY"`. Defaults to `"RGB"`. * **max_buffer_len** (int) - Optional - The depth of the ring buffer used for threaded capture. Defaults to 16. * **backend** (str) - Optional - The capture backend to use. Options: `"dxgi"` or `"winrt"`. Defaults to `"dxgi"`. * **processor_backend** (str) - Optional - The post-processing backend. Options: `"cv2"` or `"numpy"`. Defaults to `"cv2"`. ### Returns * `DXCamera` - An instance of the DXCamera class. ### Example ```python import dxcam # Default configuration camera = dxcam.create() # Explicit configuration camera = dxcam.create( device_idx=0, output_idx=0, region=(0, 0, 1920, 1080), output_color="BGR", max_buffer_len=16, backend="dxgi", processor_backend="cv2" ) frame = camera.grab() camera.release() ``` ``` -------------------------------- ### Create and Grab Frame with DXcam Source: https://github.com/ra1nty/dxcam/blob/main/README.md Basic usage to create a camera instance and grab a single frame. The 'with' statement ensures resources are released automatically. ```python import dxcam with dxcam.create() as camera: frame = camera.grab() ``` -------------------------------- ### dxcam.create() Source: https://context7.com/ra1nty/dxcam/llms.txt Creates a DXCamera instance, allowing specification of device, output, color format, and backend for capture. ```APIDOC ## dxcam.create() ### Description Creates a `DXCamera` instance. You can specify the graphics device, output index, desired color format, and the capture backend (e.g., 'dxgi' or 'winrt'). Each unique combination of `(device_idx, output_idx, backend)` maps to a distinct `DXCamera` singleton instance. ### Method `create( device_idx: int = 0, output_idx: int = 0, output_color: str = "BGRA", backend: str = "dxgi", max_buffer_len: int = 1 )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **device_idx** (int, optional): The index of the graphics device to use. Defaults to `0`. - **output_idx** (int, optional): The index of the output on the specified device. Defaults to `0`. - **output_color** (str, optional): The desired color format for the captured frames (e.g., "BGRA", "BGR", "RGB"). Defaults to "BGRA". - **backend** (str, optional): The capture backend to use ('dxgi' or 'winrt'). Defaults to 'dxgi'. - **max_buffer_len** (int, optional): The maximum number of frames to store in the internal buffer. Defaults to `1`. ### Request Example ```python import dxcam # Create a camera for the primary monitor (device 0, output 0) in BGR format camera_bgr = dxcam.create(output_color="BGR") # Create a camera for a secondary monitor (device 0, output 1) using WinRT backend camera_winrt = dxcam.create(device_idx=0, output_idx=1, backend="winrt") # Multi-monitor capture example cam0 = dxcam.create(device_idx=0, output_idx=0, output_color="RGB") cam1 = dxcam.create(device_idx=0, output_idx=1, output_color="RGB") frame0 = cam0.grab() # Assuming grab() is a valid method frame1 = cam1.grab() # Assuming grab() is a valid method cam0.release() cam1.release() ``` ### Response #### Success Response (200) A `DXCamera` instance configured with the specified parameters. #### Response Example ```json { "camera_instance": "DXCamera object" } ``` ``` -------------------------------- ### Create DXCamera Instance Source: https://github.com/ra1nty/dxcam/blob/main/README.md Creates a DXCamera instance. You can specify the backend and processor backend. If not specified, it uses default values. ```APIDOC ## Create DXCamera Instance ### Description Creates a DXCamera instance. You can specify the backend and processor backend. If not specified, it uses default values. ### Method `dxcam.create()` ### Parameters #### Keyword Arguments - **backend** (str) - Optional - Specifies the capture backend (e.g., "dxgi"). Defaults to "dxgi". - **processor_backend** (str) - Optional - Specifies the processor backend (e.g., "cv2"). Defaults to "cv2". - **output_idx** (int) - Optional - The index of the output to capture from. - **output_color** (str) - Optional - The desired output color format (e.g., "BGR", "BGRA"). Defaults to "BGRA". - **device_idx** (int) - Optional - The index of the graphics device to use. ``` -------------------------------- ### Run Static Quality Checks Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Execute static analysis checks for 'ruff' and 'ty' on the 'dxcam' package using 'uv run'. ```bash uv run ruff check dxcam uv run ty check dxcam ``` -------------------------------- ### Multi-Monitor/GPU Capture with DXCamera Source: https://context7.com/ra1nty/dxcam/llms.txt Create separate DXCamera instances for each target output using `device_idx` and `output_idx`. Use `output_info()` to enumerate available hardware. ```python import dxcam print(dxcam.output_info()) # Device[0] Output[0]: Res:(1920, 1080) Rot:0 Primary:True # Device[0] Output[1]: Res:(2560, 1440) Rot:0 Primary:False cam0 = dxcam.create(device_idx=0, output_idx=0, output_color="RGB") cam1 = dxcam.create(device_idx=0, output_idx=1, output_color="RGB") frame0 = cam0.grab() # primary 1080p monitor frame1 = cam1.grab() # secondary 1440p monitor cam0.release() cam1.release() ``` -------------------------------- ### Instant-Replay Buffer with PyAV Source: https://context7.com/ra1nty/dxcam/llms.txt This snippet demonstrates how to create an instant-replay buffer using PyAV to save captured frames to a video file. It utilizes a deque for buffering and PyAV for encoding frames. ```python from collections import deque from threading import Lock import dxcam, av TARGET_FPS = 60 BUFFER_SECONDS = 10 buffer: deque = deque(maxlen=TARGET_FPS * BUFFER_SECONDS) lock = Lock() camera = dxcam.create(output_color="RGB") camera.start(target_fps=TARGET_FPS, video_mode=True) container = av.open("replay.mp4", mode="w") stream = container.add_stream("mpeg4", rate=TARGET_FPS) stream.pix_fmt, stream.width, stream.height = "yuv420p", 1920, 1080 while True: # replace with your stop condition frame = camera.get_latest_frame() if frame is None: continue vf = av.VideoFrame.from_ndarray(frame, format="rgb24") with lock: for packet in stream.encode(vf): buffer.append(packet) # To save: write buffer packets to a new container camera.stop() camera.release() container.close() ``` -------------------------------- ### dxcam.device_info() / dxcam.output_info() Source: https://context7.com/ra1nty/dxcam/llms.txt These functions enumerate the available graphics devices (adapters) and their associated outputs (monitors), providing formatted strings with hardware details. ```APIDOC ## dxcam.device_info() / dxcam.output_info() ### Description Convenience helper functions to enumerate DXGI adapters and their attached monitors, returning formatted strings with hardware information. ### `dxcam.device_info()` Returns a string describing the available DXGI adapters. ### `dxcam.output_info()` Returns a string describing the outputs (monitors) attached to each DXGI adapter. ### Example ```python import dxcam print(dxcam.device_info()) # Example Output: # Device[0]: print(dxcam.output_info()) # Example Output: # Device[0] Output[0]: Res:(1920, 1080) Rot:0 Primary:True # Device[0] Output[1]: Res:(2560, 1440) Rot:0 Primary:False ``` ``` -------------------------------- ### Run Tests Source: https://github.com/ra1nty/dxcam/blob/main/CONTRIBUTING.md Execute the test suite for the project using 'uv run pytest -q'. ```bash uv run pytest -q ``` -------------------------------- ### Create DXcam Camera with Max Buffer Length Source: https://github.com/ra1nty/dxcam/blob/main/README.md Initialize DXcam with a specified maximum buffer length. The default is 8 frames. ```python camera = dxcam.create(max_buffer_len=120) ``` -------------------------------- ### Consume Frames with DXCamera.get_latest_frame() Source: https://context7.com/ra1nty/dxcam/llms.txt Blocks until a new frame is available and returns it. Optionally returns a frame and its hardware timestamp. Use get_latest_frame_view() for zero-copy access. ```python import dxcam camera = dxcam.create(output_color="RGB", backend="dxgi") camera.start(target_fps=60) # Frame only frame = camera.get_latest_frame() print(frame.shape) # e.g. (1080, 1920, 3) # Frame + hardware timestamp frame, ts = camera.get_latest_frame(with_timestamp=True) print(f"timestamp: {ts:.6f}s") # Zero-copy view variant view = camera.get_latest_frame_view() view_with_ts = camera.get_latest_frame_view(with_timestamp=True) camera.stop() camera.release() ``` -------------------------------- ### Zero-Copy Frame Grab with Context Manager Source: https://context7.com/ra1nty/dxcam/llms.txt Use grab_view() for a zero-copy frame, which returns a view backed by internal memory. Copy the array if the data needs to persist beyond the next capture. The 'with' statement ensures the camera is released. ```python import dxcam import numpy as np with dxcam.create(output_color="BGRA") as camera: view = camera.grab_view() if view is not None: # Must copy before next grab or start() frame = np.array(view) print(frame.shape) # (1080, 1920, 4) ``` -------------------------------- ### Inspect DXcam Device and Output Information Source: https://github.com/ra1nty/dxcam/blob/main/README.md Utility functions to list available graphics devices and their associated outputs, including resolution and primary status. This helps in selecting the correct `device_idx` and `output_idx`. ```python import dxcam print(dxcam.device_info()) print(dxcam.output_info()) ``` -------------------------------- ### DXCamera.grab_view() Source: https://context7.com/ra1nty/dxcam/llms.txt Provides a zero-copy view of the latest captured frame, allowing for faster access to frame data at the cost of potential buffer overwrites. ```APIDOC ## DXCamera.grab_view() ### Description A shorthand method for `grab(copy=False)`. It returns a view into the internal memory buffer of the captured frame. If you need to retain the frame data beyond the next capture call, you must explicitly copy the array. ### Returns * `numpy.ndarray` or `None` - A NumPy array view of the captured frame, or `None` if no frame is available. The data in this view may be overwritten by subsequent capture operations. ### Example ```python import dxcam import numpy as np with dxcam.create(output_color="BGRA") as camera: view = camera.grab_view() if view is not None: # Copy the data if you need to keep it frame = np.array(view) print(frame.shape) # Example: (1080, 1920, 4) ``` ``` -------------------------------- ### Device and Output Information Source: https://github.com/ra1nty/dxcam/blob/main/README.md Provides information about available graphics devices and their associated outputs, useful for selecting the correct device and output for capture. ```APIDOC ## Device and Output Information ### Description Provides information about available graphics devices and their associated outputs, useful for selecting the correct device and output for capture. ### Functions - **`dxcam.device_info()`**: Returns a string describing available graphics devices. - **`dxcam.output_info()`**: Returns a string describing the outputs associated with each device. ``` -------------------------------- ### Release DXcam Resources Source: https://github.com/ra1nty/dxcam/blob/main/README.md Manually stops capture, frees buffers, and releases resources. After release, the instance cannot be reused. The context manager (`with` statement) provides automatic resource management. ```python camera = dxcam.create(output_idx=0, output_color="BGR") camera.release() # camera.start() # raises RuntimeError ``` ```python with dxcam.create() as camera: frame = camera.grab() # resource released automatically ``` -------------------------------- ### DXCamera.grab() Source: https://context7.com/ra1nty/dxcam/llms.txt Captures a single frame from the configured screen source. It can return the latest frame, a specific region, or a zero-copy view. ```APIDOC ## DXCamera.grab() ### Description Grabs a single frame from the DXGI/WinRT duplicator. If `new_frame_only` is `True`, it returns `None` if no new frame has been rendered since the last call. When threaded capture is active, this method reads from the internal ring buffer. ### Parameters * **new_frame_only** (bool) - Optional - If `True`, returns `None` if no new frame is available. Defaults to `True`. * **region** (tuple) - Optional - A specific capture region defined as `(left, top, right, bottom)`. If not specified, the entire configured region is captured. * **copy** (bool) - Optional - If `True`, returns a copy of the frame data. If `False`, returns a zero-copy view into the internal buffer. Defaults to `True`. ### Returns * `numpy.ndarray` or `None` - A NumPy array representing the captured frame (shape `(H, W, C)`, dtype `uint8`), or `None` if `new_frame_only` is `True` and no new frame is available. ### Example ```python import dxcam camera = dxcam.create(output_color="RGB") # Get the latest frame, potentially None if no new frame frame = camera.grab() # Always get the last available frame frame = camera.grab(new_frame_only=False) # Capture a specific region left = (1920 - 640) // 2 top = (1080 - 640) // 2 frame = camera.grab(region=(left, top, left + 640, top + 640)) # frame.shape will be (640, 640, 3) # Get a zero-copy view (faster, but data may be overwritten) view = camera.grab(copy=False) camera.release() ``` ``` -------------------------------- ### Release DXCamera Resources Source: https://context7.com/ra1nty/dxcam/llms.txt Stops capture, frees DXGI/WinRT resources, and invalidates the instance. Using the context-manager protocol is the preferred way to ensure automatic release. ```python import dxcam # Explicit release camera = dxcam.create(output_color="BGR") frame = camera.grab() camera.release() print(camera.is_released) # True # Context manager (preferred) with dxcam.create(output_color="RGB") as camera: frame = camera.grab() # camera.release() called automatically on exit ``` -------------------------------- ### Grab Single Frame Source: https://github.com/ra1nty/dxcam/blob/main/README.md Captures a single frame from the screen. Can capture the entire screen or a specific region. Supports zero-copy views for performance. ```APIDOC ## Grab Single Frame ### Description Captures a single frame from the screen. Can capture the entire screen or a specific region. Supports zero-copy views for performance. ### Method `camera.grab()` ### Parameters #### Keyword Arguments - **region** (tuple) - Optional - A tuple `(left, top, right, bottom)` defining the capture region. - **new_frame_only** (bool) - Optional - If True, returns None if no new frame is available. Defaults to True. - **copy** (bool) - Optional - If False, returns a zero-copy view. Defaults to True. ### Returns - **numpy.ndarray** - The captured frame as a NumPy array, or a zero-copy view if `copy=False`. - **None** - If `new_frame_only=True` and no new frame is available. ``` -------------------------------- ### Set Output Color Format Source: https://github.com/ra1nty/dxcam/blob/main/README.md Specifies the color format for captured frames when creating a DXcam instance. Supported formats include RGB, RGBA, BGR, BGRA, and GRAY. BGRA is recommended for minimal dependencies. ```python dxcam.create(output_color="BGRA") ``` -------------------------------- ### Capture to Video File using OpenCV and DXCamera Source: https://context7.com/ra1nty/dxcam/llms.txt Integrates DXCamera with OpenCV's VideoWriter to save captured frames to a video file. Ensure the output color format matches OpenCV's expectations (e.g., BGR). ```python import cv2 import dxcam TARGET_FPS = 60 FRAMES = 600 camera = dxcam.create(output_color="BGR", max_buffer_len=32) camera.start(target_fps=TARGET_FPS, video_mode=True) writer = cv2.VideoWriter( "output.mp4", cv2.VideoWriter_fourcc(*"mp4v"), TARGET_FPS, (camera.width, camera.height), ) try: for _ in range(FRAMES): frame = camera.get_latest_frame() if frame is not None: writer.write(frame) finally: camera.stop() camera.release() writer.release() ``` -------------------------------- ### Grab Single Frame Source: https://context7.com/ra1nty/dxcam/llms.txt Capture a single frame using camera.grab(). It can return None if no new frame is available (when new_frame_only=True), read from a ring buffer if threaded capture is active, or capture a specific region. Use copy=False for a zero-copy view. ```python import dxcam camera = dxcam.create(output_color="RGB") # One-shot — returns None if no new frame since last call frame = camera.grab() # Always return the last available frame (never None after first frame) frame = camera.grab(new_frame_only=False) # Capture a specific region: (left, top, right, bottom) left = (1920 - 640) // 2 top = (1080 - 640) // 2 frame = camera.grab(region=(left, top, left + 640, top + 640)) # frame.shape == (640, 640, 3) # Zero-copy view — fast but buffer may be overwritten by the next grab view = camera.grab(copy=False) # or equivalently: view = camera.grab_view() owned = view.copy() if view is not None else None camera.release() ``` -------------------------------- ### DXCamera.get_latest_frame() Source: https://context7.com/ra1nty/dxcam/llms.txt Blocks until a new frame is available and returns it. Optionally, it can also return the frame's hardware timestamp. ```APIDOC ## DXCamera.get_latest_frame() ### Description Blocks until a new frame is available in the ring buffer and returns it. Optionally, it can return a `(frame, timestamp_seconds)` tuple. The timestamp source depends on the backend used. ### Method `get_latest_frame(with_timestamp: bool = False)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **with_timestamp** (bool, optional): If `True`, returns a tuple containing the frame and its hardware timestamp in seconds. Defaults to `False`. ### Request Example ```python import dxcam camera = dxcam.create(output_color="RGB", backend="dxgi") camera.start(target_fps=60) # Frame only frame = camera.get_latest_frame() print(frame.shape) # Frame + hardware timestamp frame, ts = camera.get_latest_frame(with_timestamp=True) print(f"timestamp: {ts:.6f}s") # Zero-copy view variants view = camera.get_latest_frame_view() view_with_ts = camera.get_latest_frame_view(with_timestamp=True) camera.stop() camera.release() ``` ### Response #### Success Response (200) - **frame** (numpy.ndarray): The captured video frame. - **timestamp_seconds** (float, optional): The hardware timestamp of the frame in seconds, if `with_timestamp` is `True`. #### Response Example ```json { "frame": "numpy.ndarray", "timestamp_seconds": 1678886400.123456 } ``` ``` -------------------------------- ### Grab a Single Frame with DXcam Source: https://github.com/ra1nty/dxcam/blob/main/README.md Captures a single frame from the camera. By default, it returns a numpy.ndarray. Use `new_frame_only=False` to ensure a frame is always returned, and `copy=False` or `grab_view()` for zero-copy access. ```python frame = camera.grab() ``` ```python frame = camera.grab(new_frame_only=False) ``` ```python frame = camera.grab(copy=False) ``` ```python frame_view = camera.grab_view() ``` -------------------------------- ### Release Resources Source: https://github.com/ra1nty/dxcam/blob/main/README.md Stops any ongoing capture, frees allocated buffers, and releases underlying capture resources. The camera instance cannot be reused after calling `release()`. ```APIDOC ## Release Resources ### Description Stops any ongoing capture, frees allocated buffers, and releases underlying capture resources. The camera instance cannot be reused after calling `release()`. ### Method `camera.release()` ``` -------------------------------- ### DXCamera.release() Source: https://context7.com/ra1nty/dxcam/llms.txt Stops capture, frees associated resources, and invalidates the camera instance. This method is automatically called when using the camera as a context manager. ```APIDOC ## DXCamera.release() ### Description Stops capture, frees DXGI/WinRT resources, and permanently invalidates the instance. After `release()`, all method calls raise `RuntimeError`. The context-manager protocol calls `release()` automatically. ### Method `release()` ### Parameters None ### Request Example ```python import dxcam # Explicit release camera = dxcam.create(output_color="BGR") frame = camera.grab() # Assuming grab() is a valid method camera.release() print(camera.is_released) # True # Context manager (preferred) with dxcam.create(output_color="RGB") as camera: frame = camera.grab() # camera.release() called automatically on exit ``` ### Response #### Success Response (200) None (operation is in-place) #### Response Example None ``` -------------------------------- ### DXCamera.latest_frame_time / DXCamera.latest_frame_ticks Source: https://context7.com/ra1nty/dxcam/llms.txt Properties that provide the timestamp of the most recently buffered frame, either converted to seconds or as raw hardware ticks. ```APIDOC ## DXCamera.latest_frame_time / DXCamera.latest_frame_ticks ### Description Properties that return the timestamp of the most recently buffered frame. `latest_frame_time` converts hardware ticks to seconds, while `latest_frame_ticks` returns the raw monotonic tick count from the backend. ### Properties - **latest_frame_time** (float or None): The timestamp of the most recent frame in seconds. - **latest_frame_ticks** (int or None): The raw hardware tick count of the most recent frame. ### Parameters None ### Request Example ```python import dxcam camera = dxcam.create(backend="dxgi") camera.start(target_fps=60) frame = camera.get_latest_frame() ts_seconds = camera.latest_frame_time # float or None raw_ticks = camera.latest_frame_ticks # int or None print(f"Frame at {ts_seconds:.4f}s (ticks={raw_ticks})") camera.stop() camera.release() ``` ### Response #### Success Response (200) - **latest_frame_time**: Timestamp in seconds (float) or None. - **latest_frame_ticks**: Raw timestamp ticks (int) or None. #### Response Example ```json { "latest_frame_time": 1678886400.123456, "latest_frame_ticks": 1234567890 } ``` ``` -------------------------------- ### Consume Screen Capture Data Source: https://github.com/ra1nty/dxcam/blob/main/README.md Retrieves the latest captured frame from the ring buffer. This method blocks until a new frame is available. Variants include timestamp retrieval and zero-copy views. ```python for _ in range(1000): frame = camera.get_latest_frame() # blocks until a frame is available ``` ```python frame, frame_timestamp = camera.get_latest_frame(with_timestamp=True) ``` ```python frame_view = camera.get_latest_frame_view() ``` -------------------------------- ### Capture a Specific Region Source: https://github.com/ra1nty/dxcam/blob/main/README.md Captures a frame from a defined rectangular region on the screen. The region is specified as a tuple of (left, top, right, bottom) coordinates. ```python left, top = (1920 - 640) // 2, (1080 - 640) // 2 right, bottom = left + 640, top + 640 frame = camera.grab(region=(left, top, right, bottom)) # numpy.ndarray of size (640x640x3) -> (HXWXC) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.