### Rust Option `and` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Demonstrates the `and` method for Option, which returns `None` if the first option is `None`, or the second option if the first is `Some`. ```Rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### Rust Option::is_none_or() Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Demonstrates the `is_none_or()` method for Rust's `Option`, which returns `true` if the `Option` is `None` or if its contained value satisfies a predicate function. The examples cover cases where the predicate is true for a `Some` value, false for a `Some` value, and true for a `None` value. It also includes an example with a `String`. ```rust let x: Option = Some(2); assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_none_or(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Rust Option `or` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Demonstrates the `or` method, which returns the first option if it is `Some`, otherwise returns the second option. Arguments are eagerly evaluated. ```Rust let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); let x: Option = None; let y = None; assert_eq!(x.or(y), None); ``` -------------------------------- ### Rust Option `xor` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Shows the `xor` method, which returns `Some` if exactly one of the two options is `Some`, otherwise returns `None`. ```Rust let x = Some(2); let y: Option = None; assert_eq!(x.xor(y), Some(2)); let x: Option = None; let y = Some(2); assert_eq!(x.xor(y), Some(2)); let x = Some(2); let y = Some(2); assert_eq!(x.xor(y), None); let x: Option = None; let y: Option = None; assert_eq!(x.xor(y), None); ``` -------------------------------- ### Rust: Option::is_none Method Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Provides examples for the `is_none` method on Rust's `Option` type. This method returns `true` if the `Option` is `None`, indicating the absence of a value, and `false` otherwise. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### Rust: Option::as_ref Method Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Shows an example of the `as_ref` method for `Option` in Rust. This method converts an `&Option` into an `Option<&T>`, allowing immutable borrowing of the contained value without moving it. This is useful for operations like mapping without taking ownership. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {:?}", text); ``` -------------------------------- ### Rust Option::as_slice() Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Shows the `as_slice()` method for Rust's `Option`, which returns a slice of the contained value if it exists, or an empty slice if the `Option` is `None`. This can unify iteration over `Option`s and slices. The example verifies the output for `Some(1234)` and `None`. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` -------------------------------- ### Rust Option `or_else` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Illustrates the `or_else` method, which returns the first option if it is `Some`, otherwise lazily evaluates a closure that returns an `Option`. ```Rust fn nobody() -> Option<&'static str> { None } fn vikings() -> Option<&'static str> { Some("vikings") } assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); assert_eq!(None.or_else(vikings), Some("vikings")); assert_eq!(None.or_else(nobody), None); ``` -------------------------------- ### Rust Option::is_none() Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Illustrates the `is_none()` method for Rust's `Option` type. This method returns `true` if the `Option` is `None` and `false` if it contains a value (`Some(...)`). The examples cover checks for both `Some` and `None` variants of an `Option`. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### Rust Option::as_ref() Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Illustrates how to use `as_ref()` on Rust's `Option` to obtain an `Option` containing a reference to the inner value without consuming the original `Option`. This is useful for inspecting the value inside an `Option` without taking ownership, as shown in the example calculating the length of an `Option`. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {:?}", text); ``` -------------------------------- ### Rust Option map_or Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Maps an Option to a value by providing a default if the Option is None, or applying a function to the contained value if it is Some. Arguments are eagerly evaluated. ```rust let x = Some("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Option<&str> = None; assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Rust Option::is_some_and() Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Shows the `is_some_and()` method for Rust's `Option`, which checks if the `Option` is `Some` and its contained value satisfies a given predicate function. The examples illustrate cases where the predicate evaluates to true for a `Some` value, false for a `Some` value, and false for a `None` value. It also demonstrates usage with a `String`. ```rust let x: Option = Some(2); assert_eq!(x.is_some_and(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Create EncoderInitParams Builder - Rust Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/safe/struct Initializes a new builder for EncoderInitParams, which wraps NV_ENC_INITIALIZE_PARAMS. This is the starting point for configuring NVIDIA video encoding parameters. ```rust pub fn new(encode_guid: GUID, width: u32, height: u32) -> Self ``` -------------------------------- ### Build NV_ENC_INITIALIZE_PARAMS (Rust) Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/builders Creates a builder for the `NV_ENC_INITIALIZE_PARAMS` struct. This struct is used to initialize the encoder and requires basic parameters like GUID, width, and height. It supports setting preset GUIDs, custom encode configurations, display aspect ratio, framerate, and enabling picture type decision. ```rust impl NV_ENC_INITIALIZE_PARAMS { /// Builder for [`NV_ENC_INITIALIZE_PARAMS`]. #[must_use] pub fn new(encode_guid: GUID, width: u32, height: u32) -> Self { NV_ENC_INITIALIZE_PARAMS { version: NV_ENC_INITIALIZE_PARAMS_VER, encodeGUID: encode_guid, encodeWidth: width, encodeHeight: height, ..Default::default() } } /// Specifies the preset for encoding. If the preset GUID is set then /// the preset configuration will be applied before any other parameter. pub fn preset_guid(&mut self, preset_guid: GUID) -> &mut Self { self.presetGUID = preset_guid; self } /// Specifies the advanced codec specific structure. If client has sent a /// valid codec config structure, it will override parameters set by the /// [`NV_ENC_INITIALIZE_PARAMS::preset_guid`]. /// /// The client can query the interface for codec-specific parameters /// using [`Encoder::get_preset_config`](super::encoder::Encoder::get_preset_config). /// It can then modify (if required) some of the codec config parameters and /// send down a custom config structure using this method. Even in this /// case the client is recommended to pass the same preset GUID it has /// used to get the config. pub fn encode_config(&mut self, encode_config: &mut NV_ENC_CONFIG) -> &mut Self { self.encodeConfig = encode_config; self } /// Specifies the display aspect ratio (H264/HEVC) or the render /// width/height (AV1). pub fn display_aspect_ratio(&mut self, width: u32, height: u32) -> &mut Self { self.darWidth = width; self.darHeight = height; self } /// Specifies the framerate in frames per second as a fraction /// `numerator / denominator`. pub fn framerate(&mut self, numerator: u32, denominator: u32) -> &mut Self { self.frameRateNum = numerator; self.frameRateDen = denominator; self } /// Enable the Picture Type Decision to be taken by the /// `NvEncodeAPI` interface. pub fn enable_picture_type_decision(&mut self) -> &mut Self { self.enablePTD = 1; self } // TODO: Add other options } ``` -------------------------------- ### Rust Option `get_or_insert` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Illustrates the `get_or_insert` method, which inserts a value only if the `Option` is `None`, returning a mutable reference to the contained value. ```Rust let mut x = None; { let y: &mut u32 = x.get_or_insert(5); assert_eq!(y, &5); *y = 7; } assert_eq!(x, Some(7)); ``` -------------------------------- ### Get Profile GUIDs Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of supported encode profile GUIDs for a given codec GUID. ```APIDOC ## GET /encode/profiles/{encode_guid} ### Description Retrieves a list of supported encode profile GUIDs for a specified codec GUID. This is useful for selecting specific encoding standards within a codec. ### Method GET ### Endpoint /encode/profiles/{encode_guid} ### Parameters #### Path Parameters - **encode_guid** (GUID) - Required - The GUID of the codec for which to retrieve profiles. ### Request Example None ### Response #### Success Response (200) - **profile_guids** (array of GUID) - A list of GUIDs representing supported encoding profiles for the given codec. #### Response Example ```json { "profile_guids": [ "0x4832363450524f46494c455f4849474800", "0x4832363450524f46494c455f4d454449554d00" ] } ``` ### Errors - **Invalid Encode GUID**: The provided `encode_guid` is not supported. - **Memory Error**: Could occur if the system runs out of memory. ``` -------------------------------- ### Get Preset GUIDs Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of supported encode preset GUIDs for a given codec GUID. ```APIDOC ## GET /encode/presets/{encode_guid} ### Description Retrieves a list of supported encode preset GUIDs for a specified codec GUID. This helps in determining the available performance/quality trade-offs for encoding. ### Method GET ### Endpoint /encode/presets/{encode_guid} ### Parameters #### Path Parameters - **encode_guid** (GUID) - Required - The GUID of the codec for which to retrieve presets. ### Request Example None ### Response #### Success Response (200) - **preset_guids** (array of GUID) - A list of GUIDs representing supported encoding presets for the given codec. #### Response Example ```json { "preset_guids": [ "0x50310000", "0x50320000" ] } ``` ### Errors - **Invalid Encode GUID**: The provided `encode_guid` is not supported. - **Memory Error**: Could occur if the system runs out of memory. ``` -------------------------------- ### NVIDIA Video Codec SDK Encoding API Usage Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/index Demonstrates the typical workflow for using the NVIDIA Video Codec SDK's encoder API. It outlines the initialization, configuration, buffer creation, and encoding steps. This example assumes a CUDA device for initialization and focuses on the Rust API. ```rust 1. Initialize an `Encoder` with an encode device (such as CUDA). 2. Configure the encoder and start a `Session`. 3. Create input `Buffer`s (or `RegisteredResource`) and output `Bitstream`s. 4. Encode frames with `Session::encode_picture`. ``` -------------------------------- ### Get Profile GUIDs Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of profile GUIDs supported by the encoder for a given codec GUID. This is useful for determining which encoding profiles are available on the system. ```APIDOC ## GET /api/profiles ### Description Retrieves a list of profile GUIDs supported by the encoder for a given codec GUID. This is useful for determining which encoding profiles are available on the system. ### Method GET ### Endpoint /api/profiles ### Parameters #### Query Parameters - **encode_guid** (GUID) - Required - The GUID of the codec for which to retrieve profile information. ### Request Example ```json { "encode_guid": "NV_ENC_CODEC_H264_GUID" } ``` ### Response #### Success Response (200) - **profile_guids** (Array) - A list of GUIDs representing the supported encoding profiles. #### Response Example ```json { "profile_guids": [ "NV_ENC_H264_PROFILE_BASELINE_GUID", "NV_ENC_H264_PROFILE_MAIN_GUID", "NV_ENC_H264_PROFILE_HIGH_GUID" ] } ``` ``` -------------------------------- ### Create Video Source - nvcuvid SDK Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/index This function creates a video source instance for the NVIDIA Video Codec SDK. It requires parameters defining the source configuration and likely returns a handle to the created video source. ```rust pub unsafe extern "C" fn cuvidCreateVideoSource( pSourceParams: *const CUVIDSOURCEPARAMS, ) -> CUresult ``` -------------------------------- ### Get Encode GUIDs Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of supported encoder codec GUIDs that the NVIDIA hardware and SDK can encode to. ```APIDOC ## GET /encode/guids ### Description Retrieves a list of supported encoder codec GUIDs (e.g., H.264, HEVC). ### Method GET ### Endpoint /encode/guids ### Parameters None ### Request Example None ### Response #### Success Response (200) - **encode_guids** (array of GUID) - A list of GUIDs representing supported encoding codecs. #### Response Example ```json { "encode_guids": [ "0x48323634", "0x48323635" ] } ``` ### Errors - **Memory Error**: Could occur if the system runs out of memory. ``` -------------------------------- ### Get Supported Encode Preset GUIDs for a Codec Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Fetches the supported encode preset GUIDs for a given codec GUID. This allows checking for specific encoding quality/performance presets, like NV_ENC_PRESET_P1_GUID for H.264. It first queries the count and then retrieves the actual GUIDs, managing potential errors. ```rust use cudarc::driver::CudaContext; use nvidia_video_codec_sdk::{ sys::nvEncodeAPI::{NV_ENC_CODEC_H264_GUID, NV_ENC_PRESET_P1_GUID}, Encoder, }; let cuda_ctx = CudaContext::new(0).unwrap(); let encoder = Encoder::initialize_with_cuda(cuda_ctx).unwrap(); // Check if H.264 encoding is supported. let encode_guids = encoder.get_encode_guids().unwrap(); assert!(encode_guids.contains(&NV_ENC_CODEC_H264_GUID)); let preset_guids = encoder.get_preset_guids(NV_ENC_CODEC_H264_GUID).unwrap(); // Confirm that H.264 supports the P1 preset (high performance, low quality) on this machine. assert!(preset_guids.contains(&NV_ENC_PRESET_P1_GUID)); ``` -------------------------------- ### Get H.264 Profile GUIDs (Rust) Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of supported profile GUIDs for a given encode GUID, specifically for H.264 encoding. This function queries the NVIDIA Video Codec SDK for available profiles and returns them as a vector of GUIDs. It's useful for validating profile support on the target machine. ```rust /// //* Check if H.264 encoding is supported. *// /// # let encode_guids = encoder.get_encode_guids().unwrap(); /// # assert!(encode_guids.contains(&NV_ENC_CODEC_H264_GUID)); /// /// let profile_guids = encoder.get_profile_guids(NV_ENC_CODEC_H264_GUID).unwrap(); /// // Confirm that H.264 supports the HIGH profile on this machine. /// assert!(profile_guids.contains(&NV_ENC_H264_PROFILE_HIGH_GUID)); /// ``` pub fn get_profile_guids(&self, encode_guid: GUID) -> Result, EncodeError> { // Query the number of profile GUIDs. let mut profile_count = 0; unsafe { (ENCODE_API.get_encode_profile_guid_count)(self.ptr, encode_guid, &mut profile_count) } .result(self)?; // Get the profile GUIDs. let mut profile_guids = vec![GUID::default(); profile_count as usize]; let mut actual_count = 0; unsafe { (ENCODE_API.get_encode_profile_guids)( self.ptr, encode_guid, profile_guids.as_mut_ptr(), profile_count, &mut actual_count, ) } .result(self)?; profile_guids.truncate(actual_count as usize); Ok(profile_guids) } ``` -------------------------------- ### Initialize and Use Video Encoder Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk This snippet demonstrates the typical workflow for using the NVIDIA Video Codec SDK's encoder. It outlines the initialization of an `Encoder` with a device, configuration of the encoder, and the process of creating buffers and encoding frames. This requires an encode device, such as CUDA, to be available. ```rust use nvidia_video_codec_sdk::encoder::Session; use nvidia_video_codec_sdk::cuda::Device; // 1. Initialize an Encoder with an encode device (such as CUDA). let device = Device::new(0)?; // Use the first CUDA device let mut encoder = Session::new(device)?; // 2. Configure the encoder and start a Session. // Configuration details would go here, then: let mut session = encoder.start_session(config)?; // 3. Create input Buffers (or RegisteredResource) and output Bitstreams. // let mut input_buffer = ...; // let mut output_bitstream = ...; // 4. Encode frames with Session::encode_picture. // session.encode_picture(input_buffer, output_bitstream)?; ``` -------------------------------- ### Rust Option `and_then` Method Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Illustrates the `and_then` method, which is analogous to `flatmap`. It returns `None` if the option is `None`, otherwise applies a function that returns an `Option` to the contained value. ```Rust fn sq_then_to_string(x: u32) -> Option { x.checked_mul(x).map(|sq| sq.to_string()) } assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string())); assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed! assert_eq!(None.and_then(sq_then_to_string), None); ``` ```Rust let arr_2d = [["A0", "A1"], ["B0", "B1"]]; let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1)); assert_eq!(item_0_1, Some(&"A1")); let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0)); assert_eq!(item_2_0, None); ``` -------------------------------- ### Get Supported Encode Profile GUIDs for a Codec Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves the supported encode profile GUIDs for a specified codec GUID. This function is essential for verifying if a particular encoding profile, such as NV_ENC_H264_PROFILE_HIGH_GUID, is available for a given codec. It involves querying the count and then fetching the profiles, with error handling. ```rust use cudarc::driver::CudaContext; use nvidia_video_codec_sdk::{ sys::nvEncodeAPI::{NV_ENC_CODEC_H264_GUID, NV_ENC_H264_PROFILE_HIGH_GUID}, Encoder, }; let cuda_ctx = CudaContext::new(0).unwrap(); let encoder = Encoder::initialize_with_cuda(cuda_ctx).unwrap(); ``` -------------------------------- ### Rust Option::or and Option::or_else Examples Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Shows the usage of `or` and `or_else` for providing a fallback value when an `Option` is `None`. `or` evaluates its argument eagerly, while `or_else` evaluates lazily. ```Rust let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); let x: Option = None; let y = None; assert_eq!(x.or(y), None); ``` ```Rust fn nobody() -> Option<&'static str> { None } fn vikings() -> Option<&'static str> { Some("vikings") } assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); assert_eq!(None.or_else(vikings), Some("vikings")); assert_eq!(None.or_else(nobody), None); ``` -------------------------------- ### Get Supported Encoder Codec GUIDs Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of supported encoder codec GUIDs from the NVIDIA Video Codec SDK. This function queries the number of supported GUIDs and then fetches them, handling potential memory errors. It's used to determine which video codecs the system can encode to. ```rust use cudarc::driver::CudaContext; use nvidia_video_codec_sdk::{sys::nvEncodeAPI::NV_ENC_CODEC_H264_GUID, Encoder}; let cuda_ctx = CudaContext::new(0).unwrap(); let encoder = Encoder::initialize_with_cuda(cuda_ctx).unwrap(); let encode_guids = encoder.get_encode_guids().unwrap(); // Confirm that this machine support encoding to H.264. assert!(encode_guids.contains(&NV_ENC_CODEC_H264_GUID)); ``` -------------------------------- ### Get Preset Config Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves the preset configuration structure for the encoder based on the provided codec GUID, preset GUID, and tuning information. This is useful for generating and potentially modifying encoder session presets. ```APIDOC ## GET /api/preset-config ### Description Retrieves the preset configuration structure for the encoder based on the provided codec GUID, preset GUID, and tuning information. This is useful for generating and potentially modifying encoder session presets. ### Method GET ### Endpoint /api/preset-config ### Parameters #### Query Parameters - **encode_guid** (GUID) - Required - The GUID of the codec. - **preset_guid** (GUID) - Required - The GUID of the desired preset. - **tuning_info** (NV_ENC_TUNING_INFO) - Required - The tuning information for the preset. ### Request Example ```json { "encode_guid": "NV_ENC_CODEC_H264_GUID", "preset_guid": "NV_ENC_PRESET_P1_GUID", "tuning_info": "NV_ENC_TUNING_INFO_LOW_LATENCY" } ``` ### Response #### Success Response (200) - **preset_config** (Object) - An object containing the preset configuration details. #### Response Example ```json { "preset_config": { "version": 1, "codecConfig": { "h264Config": { "profileGuid": "NV_ENC_H264_PROFILE_HIGH_GUID", "levelGuid": "NV_ENC_H264_LEVEL_5_1_GUID" } }, "rcParams": { "rateControlMode": "NV_ENC_PARAMS_RC_CONSTQP" } } } ``` ``` -------------------------------- ### Get Preset Config for H.264 Encoding (Rust) Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a preset configuration structure for H.264 encoding, given the codec GUID, preset GUID, and tuning information. This function is intended for users who need to customize encoder presets beyond the standard options provided by the SDK. It requires valid GUIDs for the codec and preset, and appropriate tuning information, otherwise it may return an error. ```rust /// Get the preset config struct from the given codec GUID, preset GUID, /// and tuning info. /// /// You should use this function to generate a preset config for the /// encoder session if you want to modify the preset further. /// /// See [NVIDIA docs](https://docs.nvidia.com/video-technologies/video-codec-sdk/12.0/nvenc-video-encoder-api-prog-guide/index.html#selecting-encoder-preset-configuration) /// /// # Errors /// /// Could error if `encode_guid` or `preset_guid` is invalid, /// if `tuning_info` is set to /// [`NV_ENC_TUNING_INFO::NV_ENC_TUNING_INFO_UNDEFINED`] or /// [`NV_ENC_TUNING_INFO::NV_ENC_TUNING_INFO_COUNT`], /// or if we run out of memory. /// /// # Examples /// /// ``` /// # use cudarc::driver::CudaContext; /// # use nvidia_video_codec_sdk::{ /// # sys::nvEncodeAPI::{ /// # NV_ENC_CODEC_H264_GUID, /// # NV_ENC_PRESET_P1_GUID, ``` -------------------------------- ### Rust Option and Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Returns None if the Option is None, otherwise returns the second Option (optb). Arguments are eagerly evaluated, consider and_then for lazy evaluation. ```rust let x = Some(5); let y = Some(10); assert_eq!(x.and(y), Some(10)); let x: Option = None; let y = Some(10); assert_eq!(x.and(y), None); ``` -------------------------------- ### Get Supported Input Formats Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Fetches the buffer formats that the encoder supports for a specified codec GUID. This function helps verify if a desired buffer format is compatible with the H.264 codec on the current machine. ```APIDOC ## GET /api/input-formats ### Description Fetches the buffer formats that the encoder supports for a specified codec GUID. This function helps verify if a desired buffer format is compatible with the H.264 codec on the current machine. ### Method GET ### Endpoint /api/input-formats ### Parameters #### Query Parameters - **encode_guid** (GUID) - Required - The GUID of the codec for which to retrieve supported input formats. ### Request Example ```json { "encode_guid": "NV_ENC_CODEC_H264_GUID" } ``` ### Response #### Success Response (200) - **supported_input_formats** (Array) - A list of supported buffer format enumerations. #### Response Example ```json { "supported_input_formats": [ "NV_ENC_BUFFER_FORMAT_NV12", "NV_ENC_BUFFER_FORMAT_ARGB10" ] } ``` ``` -------------------------------- ### Get Supported Input Formats for H.264 (Rust) Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/safe/encoder Retrieves a list of buffer formats supported by the encoder for a given codec GUID, specifically H.264. This function helps in validating whether a desired input buffer format is compatible with the encoder on the current machine. It queries the NVIDIA Video Codec SDK and returns a vector of `NV_ENC_BUFFER_FORMAT` enums. ```rust /// Get the buffer formats which the encoder supports /// for the given codec GUID. /// /// You should use this function to check whether your /// machine supports the buffer format that you wish to use. /// /// See [NVIDIA docs](https://docs.nvidia.com/video-technologies/video-codec-sdk/12.0/nvenc-video-encoder-api-prog-guide/index.html#getting-supported-list-of-input-formats). /// /// # Errors /// /// Could error if the encode GUID is invalid /// or we run out of memory. /// /// # Examples /// /// ``` /// # use cudarc::driver::CudaContext; /// # use nvidia_video_codec_sdk::{ /// # sys::nvEncodeAPI::{NV_ENC_BUFFER_FORMAT, NV_ENC_CODEC_H264_GUID}, /// # Encoder, /// # }; /// # let cuda_ctx = CudaContext::new(0).unwrap(); /// let encoder = Encoder::initialize_with_cuda(cuda_ctx).unwrap(); /// /// //* Check if H.264 encoding is supported. *// /// # let encode_guids = encoder.get_encode_guids().unwrap(); /// # assert!(encode_guids.contains(&NV_ENC_CODEC_H264_GUID)); /// /// let input_guids = encoder /// .get_supported_input_formats(NV_ENC_CODEC_H264_GUID) /// .unwrap(); /// // Confirm that H.264 supports the `ARGB10` format on this machine. /// assert!(input_guids.contains(&NV_ENC_BUFFER_FORMAT::NV_ENC_BUFFER_FORMAT_ARGB10)); /// ``` pub fn get_supported_input_formats( &self, encode_guid: GUID, ) -> Result, EncodeError> { // Query the number of supported input formats. let mut format_count = 0; unsafe { (ENCODE_API.get_input_format_count)(self.ptr, encode_guid, &mut format_count) } .result(self)?; // Get the supported input formats. let mut supported_input_formats = vec![NV_ENC_BUFFER_FORMAT::NV_ENC_BUFFER_FORMAT_UNDEFINED; format_count as usize]; let mut actual_count = 0; unsafe { (ENCODE_API.get_input_formats)( self.ptr, encode_guid, supported_input_formats.as_mut_ptr(), format_count, &mut actual_count, ) } .result(self)?; supported_input_formats.truncate(actual_count as usize); Ok(supported_input_formats) } ``` -------------------------------- ### Define H.264/H.265 P1 Encoding Preset GUID Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid Defines the GUID for the P1 encoding preset, representing the highest performance setting. This preset may have B-frames enabled by default, which can conflict with Weighted Prediction. ```rust pub const NV_ENC_PRESET_P1_GUID: GUID = GUID { Data1: 0xfc0a_8d3e, Data2: 0x45f8, Data3: 0x4cf8, Data4: [0x80, 0xc7, 0x29, 0x88, 0x71, 0x59, 0xe, 0xbf], }; ``` -------------------------------- ### Rust Option `insert` Method Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Demonstrates the `insert` method, which inserts a value into the `Option`, replacing any existing value, and returns a mutable reference to the inserted value. ```Rust let mut opt = None; let val = opt.insert(1); assert_eq!(*val, 1); assert_eq!(opt.unwrap(), 1); let val = opt.insert(2); assert_eq!(*val, 2); *val = 3; assert_eq!(opt.unwrap(), 3); ``` -------------------------------- ### Define NVENC Codec GUIDs in Rust Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid This snippet defines the GUIDs for supported video encoding codecs like H.264, H.265, and AV1. These constants are used to specify the desired codec when initializing the NvEncodeAPI. ```rust /// GUID for the H.264 encoding. /// {6BC82762-4E63-4ca4-AA85-1E50F321F6BF} pub const NV_ENC_CODEC_H264_GUID: GUID = GUID { Data1: 0x6bc8_2762, Data2: 0x4e63, Data3: 0x4ca4, Data4: [0xaa, 0x85, 0x1e, 0x50, 0xf3, 0x21, 0xf6, 0xbf], }; /// GUID for the H.265 encoding. /// {790CDC88-4522-4d7b-9425-BDA9975F7603} pub const NV_ENC_CODEC_HEVC_GUID: GUID = GUID { Data1: 0x790c_dc88, Data2: 0x4522, Data3: 0x4d7b, Data4: [0x94, 0x25, 0xbd, 0xa9, 0x97, 0x5f, 0x76, 0x3], }; /// GUID for the AV1 encoding. /// {0A352289-0AA7-4759-862D-5D15CD16D254} pub const NV_ENC_CODEC_AV1_GUID: GUID = GUID { Data1: 0x0a35_2289, Data2: 0x0aa7, Data3: 0x4759, Data4: [0x86, 0x2d, 0x5d, 0x15, 0xcd, 0x16, 0xd2, 0x54], }; ``` -------------------------------- ### Define H.264/H.265 P6 Encoding Preset GUID Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid Defines the GUID for the P6 encoding preset, offering higher quality at the cost of performance. This preset's default B-frame settings can interfere with Weighted Prediction. ```rust pub const NV_ENC_PRESET_P6_GUID: GUID = GUID { Data1: 0x8e75_c279, Data2: 0x6299, Data3: 0x4ab6, Data4: [0x83, 0x2, 0xb, 0x21, 0x5a, 0x33, 0x5c, 0xf5], }; ``` -------------------------------- ### NVIDIA Video Codec SDK Functions Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/index This section lists the available functions for interacting with the NVIDIA Video Codec SDK, covering initialization, encoding, buffer management, and status retrieval. ```APIDOC ## NVIDIA Video Codec SDK Functions ### Description This API provides a set of functions for managing and utilizing the NVIDIA video encoding hardware. It covers initialization, encoding, buffer handling, configuration, and retrieving statistics and capabilities. ### Functions - **NvEncCreateBitstreamBuffer**: Creates a buffer to store the encoded bitstream. - **NvEncCreateInputBuffer**: Creates a buffer for input video frames. - **NvEncCreateMVBuffer**: Creates a buffer for motion vector data. - **NvEncDestroyBitstreamBuffer**: Destroys a bitstream buffer. - **NvEncDestroyEncoder**: Destroys the encoder instance. - **NvEncDestroyInputBuffer**: Destroys an input buffer. - **NvEncDestroyMVBuffer**: Destroys a motion vector buffer. - **NvEncEncodePicture**: Encodes a single picture. - **NvEncGetEncodeCaps**: Retrieves the encoding capabilities of the hardware. - **NvEncGetEncodeGUIDCount**: Gets the number of supported encoder GUIDs. - **NvEncGetEncodeGUIDs**: Retrieves the supported encoder GUIDs. - **NvEncGetEncodePresetConfig**: Gets the preset configuration for encoding. - **NvEncGetEncodePresetConfigEx**: Gets an extended preset configuration. - **NvEncGetEncodePresetCount**: Gets the number of supported presets. - **NvEncGetEncodePresetGUIDs**: Retrieves the supported preset GUIDs. - **NvEncGetEncodeProfileGUIDCount**: Gets the number of supported profile GUIDs. - **NvEncGetEncodeProfileGUIDs**: Retrieves the supported profile GUIDs. - **NvEncGetEncodeStats**: Retrieves encoding statistics. - **NvEncGetInputFormatCount**: Gets the number of supported input formats. - **NvEncGetInputFormats**: Retrieves the supported input formats. - **NvEncGetLastErrorString**: Gets the last error message string. - **NvEncGetSequenceParamEx**: Retrieves extended sequence parameters. - **NvEncGetSequenceParams**: Retrieves sequence parameters. - **NvEncInitializeEncoder**: Initializes the encoder. - **NvEncInvalidateRefFrames**: Invalidates reference frames. - **NvEncLockBitstream**: Locks a bitstream buffer for access. - **NvEncLockInputBuffer**: Locks an input buffer for access. - **NvEncLookaheadPicture**: Processes a lookahead picture. - **NvEncMapInputResource**: Maps an input resource for access. - **NvEncOpenEncodeSession**: Opens an encoding session. - **NvEncOpenEncodeSessionEx**: Opens an encoding session with extended parameters. - **NvEncReconfigureEncoder**: Reconfigures the encoder. - **NvEncRegisterAsyncEvent**: Registers an asynchronous event. - **NvEncRegisterResource**: Registers a resource for encoding. - **NvEncRestoreEncoderState**: Restores the encoder state. - **NvEncRunMotionEstimationOnly**: Runs motion estimation only. - **NvEncSetIOCudaStreams**: Sets CUDA streams for I/O. - **NvEncUnlockBitstream**: Unlocks a bitstream buffer. - **NvEncUnlockInputBuffer**: Unlocks an input buffer. - **NvEncUnmapInputResource**: Unmaps an input resource. - **NvEncUnregisterAsyncEvent**: Unregisters an asynchronous event. - **NvEncUnregisterResource**: Unregisters a resource. - **NvEncodeAPICreateInstance**: Creates an instance of the encode API. - **NvEncodeAPIGetMaxSupportedVersion**: Gets the maximum supported API version. ``` -------------------------------- ### Define H.264/H.265 P3 Encoding Preset GUID Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid Defines the GUID for the P3 encoding preset, balancing performance and quality. B-frames are enabled by default for certain tuning infos, which may not be compatible with Weighted Prediction. ```rust pub const NV_ENC_PRESET_P3_GUID: GUID = GUID { Data1: 0x3685_0110, Data2: 0x3a07, Data3: 0x441f, Data4: [0x94, 0xd5, 0x36, 0x70, 0x63, 0x1f, 0x91, 0xf6], }; ``` -------------------------------- ### Rust Option::and_then Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Demonstrates the use of `and_then` for chaining fallible operations that return an Option. It returns `None` if the initial option is `None`, otherwise it applies a function to the inner value and returns the result. ```Rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` ```Rust fn sq_then_to_string(x: u32) -> Option { x.checked_mul(x).map(|sq| sq.to_string()) } assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string())); assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed! assert_eq!(None.and_then(sq_then_to_string), None); ``` ```Rust let arr_2d = [["A0", "A1"], ["B0", "B1"]]; let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1)); assert_eq!(item_0_1, Some(&"A1")); let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0)); assert_eq!(item_2_0, None); ``` -------------------------------- ### Define AV1 Main Encoding Profile GUID Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid Defines the Globally Unique Identifier (GUID) for the AV1 main encoding profile. This constant is used to specify the desired AV1 profile when configuring encoding parameters. ```rust pub const NV_ENC_AV1_PROFILE_MAIN_GUID: GUID = GUID { Data1: 0x5f2a_39f5, Data2: 0xf14e, Data3: 0x4f95, Data4: [0x9a, 0x9e, 0xb7, 0x6d, 0x56, 0x8f, 0xcf, 0x97], }; ``` -------------------------------- ### Rust Option::and Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvEncodeAPI/type Returns None if the Option is None, otherwise returns the second Option provided as an argument. Arguments are eagerly evaluated. ```rust let x = Some(10); let y = Some(20); assert_eq!(x.and(y), Some(20)); let x: Option = None; let y = Some(20); assert_eq!(x.and(y), None); ``` -------------------------------- ### Define H.264/H.265 P5 Encoding Preset GUID Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/src/nvidia_video_codec_sdk/sys/guid Defines the GUID for the P5 encoding preset, prioritizing high quality. The default B-frame configuration for certain tuning infos may restrict the use of Weighted Prediction. ```rust pub const NV_ENC_PRESET_P5_GUID: GUID = GUID { Data1: 0x21c6_e6b4, Data2: 0x297a, Data3: 0x4cba, Data4: [0x99, 0x8f, 0xb6, 0xcb, 0xde, 0x72, 0xad, 0xe3], }; ``` -------------------------------- ### Create Video Parser - nvcuvid SDK Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/index This function is used to create a video parser instance within the NVIDIA Video Codec SDK. It likely requires parameters related to the parser's configuration and callbacks. The function signature implies it returns a handle to the created parser. ```rust pub unsafe extern "C" fn cuvidCreateVideoParser( pParserParams: *const CUVIDPARSERPARAMS, ) -> CUresult ``` -------------------------------- ### Rust Option ok_or Example Source: https://docs.rs/nvidia-video-codec-sdk/0.4.0/nvidia_video_codec_sdk/sys/nvcuvid/type Transforms an Option into a Result. If the Option is Some(v), it becomes Ok(v). If the Option is None, it becomes Err(err). Arguments are eagerly evaluated. ```rust let x = Some("foo"); assert_eq!(x.ok_or(0), Ok("foo")); let x: Option<&str> = None; assert_eq!(x.ok_or(0), Err(0)); ```