### Sync Example Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example demonstrating the synchronous usage of DesktopDuplicationApi to acquire frames. ```APIDOC ## Sync Example ```rust use win_desktop_duplication::DesktopDuplicationApi; // ... other code ... { // Assuming 'adapter' and 'output' are defined elsewhere let mut duplication = DesktopDuplicationApi::new(adapter, output)?; loop { output.wait_for_vsync(); let tex = duplication.acquire_next_frame_now()?; // Use the texture to encode video // ... } } ``` ``` -------------------------------- ### Usage Example: Iterate Displays - Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.Adapter_search= An example demonstrating how to use the `iter_displays` method to loop through each display attached to an adapter and perform operations on them. ```Rust for display in adapter.iter_displays(){ // use the display object } ``` -------------------------------- ### Async Example Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example demonstrating the asynchronous usage of DesktopDuplicationApi to acquire frames. ```APIDOC ## Async Example ```rust use win_desktop_duplication::duplication::DesktopDuplicationApi; async { // Assuming 'adapter' and 'output' are defined elsewhere let mut duplication = DesktopDuplicationApi::new(adapter, output)?; loop { let tex = duplication.acquire_next_vsync_frame().await?; // Use the texture to encode video } } ``` ``` -------------------------------- ### Retrieve Specific Adapter by Index or LUID Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search= This example shows how to get a specific display adapter using either its index or its LUID (Locally Unique Identifier). This is useful when you need to access a particular adapter directly rather than iterating through all of them. ```rust use win_desktop_duplication::devices::AdapterFactory; let mut fac = AdapterFactory::new(); // Retrieve by index let adapter_by_idx = fac.get_adapter_by_idx(0); // Retrieve by LUID (assuming 'luid' is a valid LUID) // let adapter_by_luid = fac.get_adapter_by_luid(luid); ``` -------------------------------- ### Async Desktop Duplication Example Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs_search= This Rust code snippet shows an example of using the `DesktopDuplicationApi` asynchronously. It demonstrates how to create a new instance of the API and then enter a loop to continuously acquire frames using `acquire_next_vsync_frame()`. The acquired texture can then be used for video encoding. ```rust use win_desktop_duplication::duplication::DesktopDuplicationApi; async { let mut duplication = DesktopDuplicationApi::new(adapter, output)?; loop { let tex = duplication.acquire_next_vsync_frame().await?; // use the texture to encode video } } ``` -------------------------------- ### Example Usage of DisplayIterator in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.DisplayIterator_search= Demonstrates how to use the `DisplayIterator` to loop through displays connected to an adapter. It requires creating an `AdapterFactory` and then obtaining an adapter by index before iterating over its displays. ```rust use win_desktop_duplication::devices::{Adapter, AdapterFactory}; let adapter = AdapterFactory::new().get_adapter_by_idx(0); for display in adapter.iter_display(){ // use display here } ``` -------------------------------- ### Initialize win_desktop_duplication Library Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/fn.co_init_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The `co_init` function is used to initialize the win_desktop_duplication library. This function has no parameters and no return value, indicating it performs a setup operation. ```rust pub fn co_init() ``` -------------------------------- ### Example: Using DisplayVSyncStream Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search= Demonstrates how to use the `DisplayVSyncStream` in an asynchronous loop. The loop continues to receive VSync signals until an unexpected error occurs in the stream. The `stream.next().await` call retrieves the next VSync signal. ```rust while let Some(()) = stream.next().await { // ... do something here // this loop only exits when there is an unexpected error in the stream. } ``` -------------------------------- ### Desktop Duplication API Module Setup (Rust) Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs Sets up the necessary imports and basic structures for the Desktop Duplication API module in Rust. It includes standard library modules, external crates like `futures` and `log`, and Windows-specific API bindings. This setup is essential for the module's functionality. ```rust use std::mem::size_of; use std::ptr::null; use std::time::Duration; use futures::StreamExt; use log::{debug, error, trace, warn}; use tokio::time; use tokio::time::{Interval, MissedTickBehavior, sleep}; use windows::core::Interface; use windows::core::Result as WinResult; use windows::Win32::Foundation::{BOOL, E_ACCESSDENIED, E_INVALIDARG, GENERIC_READ, GetLastError, POINT}; use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_11_1}; use windows::Win32::Graphics::Direct3D11::{D3D11_BIND_FLAG, D3D11_BIND_RENDER_TARGET, D3D11_CREATE_DEVICE_FLAG, D3D11_RESOURCE_MISC_FLAG, D3D11_RESOURCE_MISC_GDI_COMPATIBLE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE, D3D11_USAGE_DEFAULT, D3D11CreateDevice, ID3D11Device4, ID3D11DeviceContext4}; use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_ACCESS_DENIED, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_INVALID_CALL, DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT, IDXGIDevice4, IDXGIOutputDuplication, IDXGIResource, IDXGISurface1}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Gdi::DeleteObject; use windows::Win32::System::StationsAndDesktops::{DESKTOP_ACCESS_FLAGS, OpenInputDesktop, SetThreadDesktop}; use windows::Win32::System::StationsAndDesktops::DF_ALLOWOTHERACCOUNTHOOK; use windows::Win32::UI::WindowsAndMessaging::{CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, GetCursorInfo, GetIconInfo, HCURSOR}; use crate::devices::Adapter; use crate::errors::DDApiError; use crate::outputs::{Display, DisplayVSyncStream}; use crate::Result; use crate::texture::{Texture, TextureDesc}; ``` -------------------------------- ### Create New AdapterFactory Instance in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=std%3A%3Avec Provides the implementation for creating a new instance of AdapterFactory. This is the starting point for interacting with display adapter enumeration. ```rust pub fn new() -> Self ``` -------------------------------- ### Iterate Over Displays using DisplayIterator Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.DisplayIterator This example demonstrates how to use the DisplayIterator to loop through displays connected to a graphics adapter. It requires initializing an AdapterFactory and then iterating over the displays of a chosen adapter. The `win_desktop_duplication::devices` module is necessary for this functionality. ```rust use win_desktop_duplication::devices::{Adapter, AdapterFactory}; fn main() { let adapter = AdapterFactory::new().get_adapter_by_idx(0); for display in adapter.iter_display() { // Process each display here println!("Found display: {:?}", display); } } ``` -------------------------------- ### Get File Metadata with Error Handling Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=u32+-%3E+bool Shows how to retrieve metadata for a file path using `Path::metadata` and handle potential errors. It demonstrates successful retrieval for a root path and failure for a non-existent path, checking the specific error kind. ```rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### Get Raw Reference to IDXGIFactory6 Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/devices.rs_search=u32+-%3E+bool The as_raw_ref() method provides immutable access to the underlying IDXGIFactory6 object. This allows for direct interaction with the DXGI factory interface when necessary. ```rust pub fn as_raw_ref(&self) -> &IDXGIFactory6 { &self.fac } ``` -------------------------------- ### Get VSync Stream Signal Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.Display_search= Obtains a stream signal for the monitor's refresh rate (VSync). The documentation for `DisplayVSyncStream` provides usage examples for this stream. ```rust pub fn get_vsync_stream(&self) -> DisplayVSyncStream ``` -------------------------------- ### Retrieve Adapter by Index or LUID (Rust) Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=u32+-%3E+bool Shows how to get a specific display adapter using either its index or its LUID (Locally Unique Identifier). This is useful when you need to access a particular adapter directly. The LUID must be obtained beforehand. ```rust use win_desktop_duplication::devices::AdapterFactory; let mut fac = AdapterFactory::new(); // either let adapter = fac.get_adapter_by_idx(0); // or let adapter = fac.get_adapter_by_luid(luid); ``` -------------------------------- ### Rust Result expect Example - Recommended Usage Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=u32+-%3E+bool Provides an example of recommended usage for the `expect` method, emphasizing informative panic messages that explain why the Ok value was expected. This example demonstrates expecting an environment variable to be set. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream Documentation for `TryFrom` and `TryInto` traits, enabling fallible type conversions. ```APIDOC ## TryFrom and TryInto Implementations ### Description Provides fallible conversion between types. ### `impl TryFrom for T` #### Description Enables converting a type `U` into type `T`. #### Type Alias - **Error** (`Infallible`): The type returned in the event of a conversion error. #### Method - **try_from(value)**: Performs the conversion from `U` to `T`. ### `impl TryInto for T` #### Description Enables converting a type `T` into type `U`. #### Type Alias - **Error** (`>::Error`): The type returned in the event of a conversion error. #### Method - **try_into()**: Performs the conversion from `T` to `U`. ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search=std%3A%3Avec Demonstrates the implementation of `TryFrom` and `TryInto` traits, which allow for fallible type conversions. These are essential for scenarios where a conversion might fail and needs to be handled gracefully. ```Rust impl TryFrom for T where U: Into, { type Error = Infallible; fn try_from(value: U) -> Result>::Error> } impl TryInto for T where U: TryFrom, { type Error = >::Error; fn try_into(self) -> Result>::Error> } ``` -------------------------------- ### Rust Result expect Example - Panic Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=u32+-%3E+bool Illustrates the `expect` method, which returns the contained Ok value or panics if the value is Err. The panic message includes the provided message and the error's content. This example shows a panic scenario with a custom message. ```rust let x: Result = Err("emergency failure"); x.expect("Testing expect"); // panics with `Testing expect: emergency failure` ``` -------------------------------- ### TryFrom and TryInto Implementations Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search= These sections describe the `TryFrom` and `TryInto` traits for conversion, particularly in the context of `Result` types. ```APIDOC ## TryFrom for T ### Description Implements conversion from type `U` into type `T`. ### Method `try_from(value: U) -> Result>::Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ## TryInto for T ### Description Implements conversion from type `T` into type `U`. ### Method `try_into(self) -> Result>::Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize and Iterate AdapterFactory in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory Demonstrates how to create an AdapterFactory instance and iterate over the available display adapters using a for loop. The AdapterFactory automatically resets its iterator state. ```rust use win_desktop_duplication::devices::AdapterFactory; let mut fac = AdapterFactory::new(); for adapter in fac { // use adapter value here } ``` -------------------------------- ### into_ok Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search= Returns the contained Ok value, but never panics. This is an unstable, nightly-only API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Method `into_ok` (on Result) ### Parameters None ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response #### Success Response (Ok value) - T (type) - The contained Ok value. #### Response Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Constraints - This is a nightly-only experimental API. - `E` must implement `Into`. ``` -------------------------------- ### AdapterFactory Methods Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=u32+-%3E+bool Provides details on the methods available for the AdapterFactory, including creation, retrieval, and reset operations. ```APIDOC ## impl AdapterFactory ### `pub fn new() -> Self` **Description**: Creates a new instance of `AdapterFactory`. ### `pub fn get_adapter_by_idx(&self, idx: u32) -> Option` **Description**: Retrieves an adapter by its index. **Parameters**: * `idx` (u32) - The index of the adapter to retrieve. **Returns**: * `Option` - An `Option` containing the `Adapter` if found, otherwise `None`. ### `pub fn get_adapter_by_luid(&self, luid: LUID) -> Option` **Description**: Retrieves an adapter by its LUID (Locally Unique Identifier). **Parameters**: * `luid` (LUID) - The LUID of the adapter to retrieve. **Returns**: * `Option` - An `Option` containing the `Adapter` if found, otherwise `None`. ### `pub fn reset(&mut self)` **Description**: Resets the iterator status of `AdapterFactory`, allowing you to iterate over the adapters again from the beginning. ### `pub fn as_raw_ref(&self) -> &IDXGIFactory6` **Description**: Acquires a raw reference to the underlying `IDXGIFactory6` COM interface. **Returns**: * `&IDXGIFactory6` - A reference to the raw `IDXGIFactory6` interface. ``` -------------------------------- ### Get TypeId of Self Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=std%3A%3Avec Returns the unique `TypeId` of the implementing type. This is part of the `Any` trait and is used for runtime type identification. ```rust fn type_id(&self) -> TypeId; ``` -------------------------------- ### Rust TypeId Access Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.DisplayIterator_search=u32+-%3E+bool Demonstrates how to get the `TypeId` of a type using the `Any` trait implementation. This is often used for dynamic type checking. ```rust impl Any for T { fn type_id(&self) -> TypeId; } // Example usage: // let value: String = "hello".to_string(); // let type_id = value.type_id(); ``` -------------------------------- ### win_desktop_duplication - co_init Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/fn.co_init_search=std%3A%3Avec Initializes the COM library for the current thread. ```APIDOC ## co_init ### Description Initializes the COM library for the current thread. This function should be called before using any other COM functions or objects. ### Method Rust function call ### Endpoint N/A (Rust function) ### Parameters None ### Request Example ```rust use win_desktop_duplication::co_init; fn main() { unsafe { co_init() }; // ... use COM objects ... } ``` ### Response #### Success Response None (void function) #### Response Example N/A ``` -------------------------------- ### Create Display Instance using IDXGIOutput6 Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.Display_search= Provides a constructor for the `Display` struct, taking an `IDXGIOutput6` reference as input. This function initializes a new `Display` instance, allowing interaction with a specific monitor. ```rust pub fn new(output: IDXGIOutput6) -> Self ``` -------------------------------- ### Get Nth Element of AdapterFactory Iterator in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=std%3A%3Avec Retrieves the nth element from the AdapterFactory iterator. This method consumes elements up to the nth one. ```rust fn nth(&mut self, n: usize) -> Option ``` -------------------------------- ### Unpin Stream Polling Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search=std%3A%3Avec A specialized method for polling `Unpin` stream types, providing a convenient way to get the next item or error from the stream. ```rust fn try_poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll>> where Self: Unpin, A convenience method for calling `TryStream::try_poll_next` on `Unpin` stream types. ``` -------------------------------- ### Create DesktopDuplicationApi with Default Settings Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search= Constructor for DesktopDuplicationApi that creates a new instance using the provided adapter and display. It automatically initializes the DirectX device and context. This method may fail if the application's DPI awareness is not set correctly, requiring `crate::set_process_dpi_awareness` to be called. ```rust pub fn new(adapter: Adapter, output: Display) -> Result ``` -------------------------------- ### Get Next Item from Stream Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search= The `next` method, part of `StreamExt`, creates a future that resolves to the next item in the stream. It requires the stream to be `Unpin`. ```rust fn next(&mut self) -> Next<'_, Self> where Self: Unpin, ``` -------------------------------- ### Sync Desktop Duplication Example Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs_search= This Rust code snippet illustrates a synchronous usage pattern for the `DesktopDuplicationApi`. It shows how to initialize the API and then enter a loop that waits for vsync, acquires the next frame using `acquire_next_frame_now()`, and processes the captured texture for video encoding. ```rust use win_desktop_duplication::DesktopDuplicationApi; // .... { let mut duplication = DesktopDuplicationApi::new(adapter, output)?; loop { output.wait_for_vsync(); let tex = duplication.acquire_next_frame_now()?; // use the texture to encode video //... } } ``` -------------------------------- ### Get Raw ID3D11Texture2D Reference Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/texture/struct.Texture_search= Provides a reference to the internal ID3D11Texture2D instance, allowing direct interaction with the underlying DirectX texture object. ```rust pub fn as_raw_ref(&self) -> &ID3D11Texture2D ``` -------------------------------- ### Get Last Element of AdapterFactory Iterator in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory_search=std%3A%3Avec Consumes the AdapterFactory iterator and returns the last adapter yielded. If the iterator is empty, it returns None. ```rust fn last(self) -> Option ``` -------------------------------- ### pub fn ok(self) -> Option Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Converts a `Result` to `Option`, discarding the error. ```APIDOC ## pub fn ok(self) -> Option ### Description Converts a `Result` to `Option`, consuming `self`, and discarding the error, if any. ### Method Function ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response (200) - **Option** - The result as an Option. #### Response Example ``` let x: Result = Ok(2); assert_eq!(x.ok(), Some(2)); let x: Result = Err("Nothing here"); assert_eq!(x.ok(), None); ``` ``` -------------------------------- ### Define Texture Struct Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/texture/struct.Texture_search= Defines the Texture struct, a wrapper around ID3D11Texture2D, providing methods to get dimensions, pixel format, and pixel data. ```rust pub struct Texture { /* private fields */ } ``` -------------------------------- ### Getting Type ID Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.DisplayIterator_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E The `type_id` method, part of the `Any` trait implementation, returns the unique `TypeId` of a given type. This is useful for runtime type introspection and downcasting. ```rust fn type_id(&self) -> TypeId where T: 'static + ?Sized ``` -------------------------------- ### AdapterFactory Usage Example (Rust) Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/devices.rs_search=u32+-%3E+bool This snippet illustrates how to use the `AdapterFactory` to obtain GPU adapters. It shows two common patterns: iterating over all available adapters using a `for` loop and directly accessing a specific adapter by its index or LUID. This factory is the entry point for discovering hardware resources for desktop duplication. ```rust use win_desktop_duplication::devices::AdapterFactory; // Iterate over all adapters: let mut fac = AdapterFactory::new(); for adapter in fac { println!("Adapter Name: {}", adapter.name()); } // Get a specific adapter by index: let mut fac = AdapterFactory::new(); if let Some(adapter) = fac.get_adapter_by_idx(0) { println!("First adapter: {}", adapter.name()); } // Get a specific adapter by LUID (assuming 'my_luid' is defined): // let adapter = fac.get_adapter_by_luid(my_luid); ``` -------------------------------- ### Get Current Display Mode Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.Display_search= Retrieves the currently active display mode of the monitor. It returns a `Result` containing the `DisplayMode` on success or a `DDApiError` on failure. ```rust pub fn get_current_display_mode(&self) -> Result ``` -------------------------------- ### TryFrom and TryInto Traits Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Enables fallible conversions between types. ```APIDOC ## TryFrom and TryInto Traits ### Description These traits allow for fallible type conversions, where the conversion might fail. `TryFrom` attempts to convert a type `U` into the implementing type, returning a `Result`. `TryInto` allows the implementing type `T` to be converted into another type `U` (provided `U` implements `TryFrom`), also returning a `Result`. ### `TryFrom` Associated Types and Methods #### `type Error = Infallible` The type returned in the event of a conversion error. `Infallible` indicates that the conversion should not fail under normal circumstances defined by the trait implementation. #### `try_from(value: U) -> Result>::Error>` Performs the conversion. Returns `Ok(T)` on success or `Err(E)` on failure. ### `TryInto` Associated Types and Methods #### `type Error = >::Error` The type returned in the event of a conversion error. This mirrors the error type from the corresponding `TryFrom` implementation. #### `try_into(self) -> Result>::Error>` Performs the conversion. Returns `Ok(U)` on success or `Err(E)` on failure. ### Example ```rust use std::convert::TryFrom; let data = "123"; // Try to convert a string slice to an integer match data.parse::() { Ok(num) => println!("Parsed number: {}", num), Err(_) => println!("Failed to parse number."), } // Example using TryFrom directly (if applicable for a custom type) struct Number(i32); impl TryFrom for Number { type Error = String; fn try_from(value: String) -> Result { match value.parse::() { Ok(num) => Ok(Number(num)), Err(e) => Err(e.to_string()), } } } let s = String::from("456"); match Number::try_from(s) { Ok(num) => println!("Successfully converted string to Number: {}", num.0), Err(e) => println!("Conversion failed: {}", e), } ``` ``` -------------------------------- ### Get Owned Adapter Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.Adapter_search=u32+-%3E+bool Implements the `ToOwned` trait, defining how to create an owned version of the `Adapter` (which is `Adapter` itself in this case) from a borrowed reference. This typically involves cloning. ```rust type Owned = T; fn to_owned(&self) -> T; fn clone_into(&self, target: &mut T); ``` -------------------------------- ### Rust Crate Initialization and Module Exports Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/lib.rs_search= This Rust code snippet initializes the crate's documentation by including the README file. It then imports and re-exports various modules such as 'devices', 'outputs', 'duplication', 'errors', 'texture', and 'tex_reader'. It also exports utility functions 'co_init' and 'set_process_dpi_awareness', and defines a type alias 'Result' for handling API errors. ```rust #![doc = include_str! ("../README.md")] use crate::errors::DDApiError; pub mod devices; pub mod outputs; pub mod duplication; mod utils; pub mod errors; pub mod texture; pub mod tex_reader; pub use duplication::*; pub use utils::{co_init,set_process_dpi_awareness}; pub type Result = core::result::Result; ``` -------------------------------- ### TryStream Trait and Extensions Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search= Documentation for the `TryStream` trait and its associated extension methods. ```APIDOC ## TryStream Trait ### Description Represents a stream that yields `Result` items. ### Type Aliases - **`Ok`**: `T` - The type of successful values yielded by this stream. - **`Error`**: `E` - The type of failures yielded by this stream. ### Method - `try_poll_next(self: Pin<&mut S>, cx: &mut Context<'_>) -> Poll::Ok, ::Error>>>` Polls this `TryStream` as if it were a `Stream`. ## TryStreamExt Trait ### Description Extension methods for types implementing the `TryStream` trait. ### Methods - **`err_into(self) -> ErrInto`**: Wraps the stream to convert the error type. - **Requires**: `Self::Error: Into` - **`map_ok(self, f: F) -> MapOk`**: Maps the success value using a closure. - **Requires**: `F: FnMut(Self::Ok) -> T` - **`map_err(self, f: F) -> MapErr`**: Maps the error value using a closure. - **Requires**: `F: FnMut(Self::Error) -> E` - **`and_then(self, f: F) -> AndThen`**: Chains a computation for successful results. - **Requires**: `F: FnMut(Self::Ok) -> Fut`, `Fut: TryFuture` - **`or_else(self, f: F) -> OrElse`**: Chains a computation for error results. - **Requires**: `F: FnMut(Self::Error) -> Fut`, `Fut: TryFuture` - **`inspect_ok(self, f: F) -> InspectOk`**: Performs an action with the success value before passing it on. - **Requires**: `F: FnMut(&Self::Ok)` - **`inspect_err(self, f: F) -> InspectErr`**: Performs an action with the error value before passing it on. - **Requires**: `F: FnMut(&Self::Error)` ``` -------------------------------- ### Implement BorrowMut Trait for Generic Type T in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.DisplayVSyncStream_search=std%3A%3Avec This blanket implementation allows any type `T` to borrow mutably from itself. It provides the `borrow_mut` method to get a mutable reference to the object. ```Rust impl BorrowMut for T where T: ?Sized, ``` -------------------------------- ### win_desktop_duplication - co_init Function Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/fn.co_init_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the COM library for the current thread. ```APIDOC ## co_init ### Description Initializes the COM library for the current thread. This function must be called before any other COM functions can be used. ### Method Rust Function Call ### Endpoint N/A (local function) ### Parameters None ### Request Example ```rust use win_desktop_duplication::co_init; fn main() { unsafe { co_init() }; // COM operations can now be performed } ``` ### Response #### Success Response (None - function has a `()` return type) #### Response Example (N/A) ``` -------------------------------- ### Get Raw IDXGIOutput6 Reference Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.Display_search= Returns a reference to the internal `IDXGIOutput6` object. This allows direct access to the underlying graphics API object for advanced operations. ```rust pub fn as_raw_ref(&self) -> &IDXGIOutput6 ``` -------------------------------- ### Get Supported Display Modes Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/outputs/struct.Display_search= Fetches a list of all supported display modes for the monitor. It returns a `Result` containing a `Vec` on success or a `DDApiError` on failure. ```rust pub fn get_display_modes(&self) -> Result, DDApiError> ``` -------------------------------- ### From and Into Traits Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Enables conversion between types. ```APIDOC ## From and Into Traits ### Description These traits facilitate type conversions. `From` allows a type `T` to be converted into the implementing type, while `Into` allows the implementing type `T` to be converted into another type `U` (provided `U` implements `From`). ### `From` Methods #### `from(t: T) -> T` Returns the argument unchanged. This is a placeholder and the actual implementation defines the conversion logic. ### `Into` Methods #### `into(self) -> U` Calls `U::from(self)`. The conversion behavior is determined by the `From for U` implementation. ### Example ```rust struct MyInt(i32); impl From for MyInt { fn from(val: i32) -> Self { MyInt(val) } } let i: i32 = 5; let my_int: MyInt = MyInt::from(i); // Using From let my_int_into: MyInt = i.into(); // Using Into println!("MyInt value: {}", my_int.0); println!("MyInt value (via into): {}", my_int_into.0); ``` ``` -------------------------------- ### Create DesktopDuplicationApi with Custom DirectX Device Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/duplication/struct.DesktopDuplicationApi_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes DesktopDuplicationApi using a pre-existing DirectX device and context. This allows for greater control over the graphics pipeline, such as integrating with existing rendering systems. ```rust pub fn new_with( d3d_device: ID3D11Device4, ctx: ID3D11DeviceContext4, output: Display, ) -> Result ``` -------------------------------- ### Get Adapter Name in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.Adapter Retrieves the name of the GPU represented by the Adapter. This method returns a String indicating the adapter's model or identifier. ```rust pub fn name(&self) -> String ``` -------------------------------- ### Rust Result unwrap() - Panic Example Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=std%3A%3Avec Illustrates the panic behavior of the `unwrap()` method when called on an `Err` variant of a `Result`. The panic message will be the value contained within the `Err`. ```Rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### expect Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search=u32+-%3E+bool Returns the contained Ok value, consuming the self value. Panics if the value is Err. ```APIDOC ## POST /websites/rs-win_desktop_duplication/expect ### Description Returns the contained `Ok` value, consuming the `self` value. Panics if the value is an `Err`. ### Method POST ### Endpoint /websites/rs-win_desktop_duplication/expect ### Parameters #### Request Body - **input_result** (Result) - Required - The input Result. - **message** (String) - Required - The message to include in the panic. ### Request Example ```json { "input_result": {"Err": "emergency failure"}, "message": "Testing expect" } ``` ### Response #### Success Response (200) - **value** (T) - The contained Ok value. #### Response Example ```json { "value": 10 } ``` #### Error Response (400) - **error** (String) - Describes the panic. #### Error Example ```json { "error": "panic: Testing expect: emergency failure" } ``` ``` -------------------------------- ### Retrieve Adapter by Index or LUID in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.AdapterFactory Shows how to get a specific display adapter from the AdapterFactory using either its index or its unique system-wide LUID (Locally Unique Identifier). ```rust use win_desktop_duplication::devices::AdapterFactory; let mut fac = AdapterFactory::new(); // either let adapter = fac.get_adapter_by_idx(0); // or // let adapter = fac.get_adapter_by_luid(luid); ``` -------------------------------- ### Initialize Desktop Duplication API in Rust Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs_search=std%3A%3Avec Initializes the Desktop Duplication API, setting up the necessary environment for capturing desktop frames. This includes configuring the graphics device, output, and duplication parameters. It handles potential errors during initialization and configuration. ```rust use std::mem::size_of; use std::ptr::null; use std::time::Duration; use futures::StreamExt; use log::{debug, error, trace, warn}; use tokio::time; use tokio::time::{Interval, MissedTickBehavior, sleep}; use windows::core::Interface; use windows::core::Result as WinResult; use windows::Win32::Foundation::{BOOL, E_ACCESSDENIED, E_INVALIDARG, GENERIC_READ, GetLastError, POINT}; use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_11_1}; use windows::Win32::Graphics::Direct3D11::{D3D11_BIND_FLAG, D3D11_BIND_RENDER_TARGET, D3D11_CREATE_DEVICE_FLAG, D3D11_RESOURCE_MISC_FLAG, D3D11_RESOURCE_MISC_GDI_COMPATIBLE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE, D3D11_USAGE_DEFAULT, D3D11CreateDevice, ID3D11Device4, ID3D11DeviceContext4}; use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_ACCESS_DENIED, DXGI_ERROR_ACCESS_LOST, DXGI_ERROR_INVALID_CALL, DXGI_ERROR_SESSION_DISCONNECTED, DXGI_ERROR_UNSUPPORTED, DXGI_ERROR_WAIT_TIMEOUT, IDXGIDevice4, IDXGIOutputDuplication, IDXGIResource, IDXGISurface1}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Gdi::DeleteObject; use windows::Win32::System::StationsAndDesktops::{DESKTOP_ACCESS_FLAGS, OpenInputDesktop, SetThreadDesktop}; use windows::Win32::System::StationsAndDesktops::DF_ALLOWOTHERACCOUNTHOOK; use windows::Win32::UI::WindowsAndMessaging::{CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, GetCursorInfo, GetIconInfo, HCURSOR}; use crate::devices::Adapter; use crate::errors::DDApiError; use crate::outputs::{Display, DisplayVSyncStream}; use crate::Result; use crate::texture::{Texture, TextureDesc}; #[cfg(test)] mod test { use std::sync::Once; use std::time::{Duration, Instant}; use futures::FutureExt; use futures::select; use log::LevelFilter::Debug; use tokio::time::interval; use crate::{DDApiError, DuplicationApiOptions}; use crate::devices::AdapterFactory; use crate::duplication::DesktopDuplicationApi; use crate::outputs::DisplayMode; use crate::utils::{co_init, set_process_dpi_awareness}; static INIT: Once = Once::new(); pub fn initialize() { INIT.call_once(|| { let _ = env_logger::builder().is_test(true).filter_level(Debug).try_init(); }); } #[test] fn test_duplication() { initialize(); let rt = tokio::runtime::Builder::new_current_thread() .thread_name("graphics_thread".to_owned()).enable_time().build().unwrap(); rt.block_on(async { set_process_dpi_awareness(); co_init(); let adapter = AdapterFactory::new().get_adapter_by_idx(0).unwrap(); let output = adapter.get_display_by_idx(0).unwrap(); let mut dupl = DesktopDuplicationApi::new(adapter, output.clone()).unwrap(); let curr_mode = output.get_current_display_mode().unwrap(); dupl.configure(DuplicationApiOptions { skip_cursor: true }); let new_mode = DisplayMode { width: 1920, height: 1080, orientation: Default::default(), refresh_num: curr_mode.refresh_num, refresh_den: curr_mode.refresh_den, hdr: false, }; let mut counter = 0; let mut secs = 0; let mut interval = interval(Duration::from_secs(1)); output.set_display_mode(&new_mode).unwrap(); loop { select! { tex = dupl.acquire_next_vsync_frame().fuse()=>{ match &tex { Err(DDApiError::AccessDenied)| Err(DDApiError::AccessLost) => { println!("error: {:?}",tex.err()) } Err(e)=>{ println!("error: {:?}",e) } Ok(_)=>{ counter += 1; } } }, _ = interval.tick().fuse() => { println!("fps: {}",counter); counter = 0; secs+=1; } } } }); } } ``` -------------------------------- ### Get Adapter LUID in Rust Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.Adapter Returns the Locally Unique Identifier (LUID) of the Adapter. LUID is a system-defined value used to uniquely identify graphics adapters. ```rust pub fn luid(&self) -> LUID ``` -------------------------------- ### Skip Elements in Iterator (Rust) Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/devices/struct.DisplayIterator_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an iterator that skips a specified number of elements from the beginning. This is useful for processing data starting from a certain point, ignoring initial entries. ```Rust fn skip(self, n: usize) -> Skip where Self: Sized, ``` -------------------------------- ### Rust: Create Desktop Duplication API Instance (new) Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs_search=u32+-%3E+bool This function creates a new instance of the DesktopDuplicationApi. It takes an `Adapter` and a `Display` object as input. Internally, it creates a DirectX device and context from the provided adapter and then calls `new_with` to initialize the API. This method may fail if the process's DPI awareness is not set, requiring the use of `crate::set_process_dpi_awareness`. ```rust /// Create a new instance of Desktop Duplication api from the provided [adapter][Adapter] and /// [display][Display]. The application auto creates directx device and context from provided /// adapter. /// /// If you wish to use your own directx device, context, use [new_with][Self::new_with] method /// /// this method fails with /// * [DDApiError::Unsupported] when the application's dpi awareness is not set. use [crate::set_process_dpi_awareness] pub fn new(adapter: Adapter, output: Display) -> Result { let (device, ctx) = Self::create_device(&adapter)?; Self::new_with(device, ctx, output) } ``` -------------------------------- ### Rust Conversion Example: ColorFormat to DXGI_FORMAT Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/texture/enum.ColorFormat_search=std%3A%3Avec Demonstrates how to convert between the ColorFormat enum and DXGI_FORMAT using the `into()` method. This is useful for interoperability with DirectX and other graphics APIs that use DXGI_FORMAT. ```rust let format_dxgi: DXGI_FORMAT = ColorFormat::ARGBUNorm.into(); let format: ColorFormat = DXGI_FORMAT_R8G8B8A8_UNORM.into(); ``` -------------------------------- ### Initialize Desktop Duplication API - Rust Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/duplication.rs_search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the DesktopDuplicationApi, setting up the necessary components for capturing desktop frames. It requires an adapter and an output display, and can be configured with options like skipping the cursor. ```rust use crate::{DDApiError, DuplicationApiOptions}; use crate::devices::AdapterFactory; use crate::duplication::DesktopDuplicationApi; use crate::outputs::DisplayMode; use crate::utils::{co_init, set_process_dpi_awareness}; use std::time::Duration; use futures::select; use tokio::time::interval; // ... inside test function ... let rt = tokio::runtime::Builder::new_current_thread() .thread_name("graphics_thread".to_owned()).enable_time().build().unwrap(); rt.block_on(async { set_process_dpi_awareness(); co_init(); let adapter = AdapterFactory::new().get_adapter_by_idx(0).unwrap(); let output = adapter.get_display_by_idx(0).unwrap(); let mut dupl = DesktopDuplicationApi::new(adapter, output.clone()).unwrap(); let curr_mode = output.get_current_display_mode().unwrap(); dupl.configure(DuplicationApiOptions { skip_cursor: true }); let new_mode = DisplayMode { width: 1920, height: 1080, orientation: Default::default(), refresh_num: curr_mode.refresh_num, refresh_den: curr_mode.refresh_den, hdr: false, }; let mut counter = 0; let mut secs = 0; let mut interval = interval(Duration::from_secs(1)); output.set_display_mode(&new_mode).unwrap(); loop { select! { tex = dupl.acquire_next_vsync_frame().fuse() => { match &tex { Err(DDApiError::AccessDenied)| Err(DDApiError::AccessLost) => { println!("error: {:?}",tex.err()) } Err(e)=>{ println!("error: {:?}",e) } Ok(_)=>{ counter += 1; } } }, _ = interval.tick().fuse() => { println!("fps: {}",counter); counter = 0; secs+=1; } } } }); ``` -------------------------------- ### Initialize and Test TextureReader Source: https://docs.rs/win_desktop_duplication/latest/src/win_desktop_duplication/tex_reader.rs Initializes the logging and runtime environment, then acquires display adapter and output. Creates a DesktopDuplicationApi instance and then a TextureReader. It then enters a loop to acquire frames, read texture data into a vector, print pitch and sample data, and calculate FPS. The loop breaks after 5 seconds. ```rust use std::sync::Once; use std::time::Duration; use futures::{FutureExt, select}; use log::LevelFilter::Debug; use tokio::time::interval; use crate::{co_init, DesktopDuplicationApi, set_process_dpi_awareness}; use crate::devices::AdapterFactory; use crate::tex_reader::TextureReader; static INIT: Once = Once::new(); pub fn initialize() { INIT.call_once(|| { let _ = env_logger::builder().is_test(true).filter_level(Debug).try_init(); }); } #[test] fn test_texture_reader() { initialize(); let rt = tokio::runtime::Builder::new_current_thread() .thread_name("graphics_thread".to_owned()).enable_time().build().unwrap(); rt.block_on(async { set_process_dpi_awareness(); co_init(); let adapter = AdapterFactory::new().get_adapter_by_idx(0).unwrap(); let output = adapter.get_display_by_idx(0).unwrap(); let mut dupl = DesktopDuplicationApi::new(adapter, output.clone()).unwrap(); let (dev, ctx) = dupl.get_device_and_ctx(); let mut reader = TextureReader::new(dev, ctx); let mut counter = 0; let mut secs = 0; let mut interval = interval(Duration::from_secs(1)); let mut data = Vec::::new(); loop { select! { tex = dupl.acquire_next_vsync_frame().fuse()=>{ if let Err(e) = tex { println!("error: {:?}",e) } else { let tex = tex.unwrap(); reader.get_data(&mut data,&tex).unwrap(); let pitch = tex.desc().width as usize *4; println!("pitch: {}",pitch); for i in 0..4{ for j in 0..12{ print!("{}\t",data[pitch*(i+1)-(12-(j))]); } print!("\n"); } print!("\n"); counter += 1; }; }, _ = interval.tick().fuse() => { println!("fps: {}",counter); counter = 0; secs+=1; if secs ==5 { break; } } } ; }; }); } ``` -------------------------------- ### Get References from Result with AsRef (Rust) Source: https://docs.rs/win_desktop_duplication/latest/win_desktop_duplication/type.Result_search= Explains the `as_ref()` method, which converts a `&Result` into a `Result<&T, &E>`. This allows borrowing the contained values without consuming the original `Result`. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ```