### Start RTCRtpReceiver Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=std%3A%3Avec Transitions the RTPReceiver state to Started. ```rust pub(crate) fn start(&self) -> Result<()> { State::transition(State::Started, &self.state_tx) } ``` -------------------------------- ### start_srtp Source: https://docs.rs/webrtc/0.17.1/src/webrtc/dtls_transport/mod.rs.html?search= Initializes and starts the SRTP session. ```APIDOC ## start_srtp ### Description Initializes and starts the SRTP session. ### Signature `pub(crate) async fn start_srtp(&self) -> Result<()>` ### Returns - `Result<()>`: Ok if the SRTP session was started successfully, or an error if it failed. ``` -------------------------------- ### Create Offer Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/struct.RTCPeerConnection.html Starts the PeerConnection and generates the local Session Description (offer). Refer to the W3C specification for details. ```rust pub async fn create_offer( &self, options: Option, ) -> Result ``` -------------------------------- ### Start RTP processing Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/peer_connection_internal.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates RTP processing, handling transceiver updates and starting RTP receivers. It distinguishes between initial setup and renegotiation. ```rust pub(super) async fn start_rtp( self: &Arc, is_renegotiation: bool, remote_desc: Arc, ) -> Result<()> { let mut track_details = if let Some(parsed) = &remote_desc.parsed { track_details_from_sdp(parsed, false) } else { vec![] }; let current_transceivers = { let current_transceivers = self.rtp_transceivers.lock().await; current_transceivers.clone() }; if !is_renegotiation { self.undeclared_media_processor(); } else { for t in ¤t_transceivers { let receiver = t.receiver().await; let tracks = receiver.tracks().await; if tracks.is_empty() { continue; } let mut receiver_needs_stopped = false; for t in tracks { if !t.rid().is_empty() { if let Some(details) = track_details_for_rid(&track_details, SmolStr::from(t.rid())) { t.set_id(details.id.clone()); t.set_stream_id(details.stream_id.clone()); continue; } } else if t.ssrc() != 0 { if let Some(details) = track_details_for_ssrc(&track_details, t.ssrc()) { t.set_id(details.id.clone()); t.set_stream_id(details.stream_id.clone()); continue; } } receiver_needs_stopped = true; } if !receiver_needs_stopped { continue; } log::info!("Stopping receiver {:?}", receiver); if let Err(err) = receiver.stop().await { log::warn!("Failed to stop RtpReceiver: {}", err); continue; } let interceptor = self .interceptor .upgrade() .ok_or(Error::ErrInterceptorNotBind)?; let receiver = Arc::new(RTCRtpReceiver::new( self.setting_engine.get_receive_mtu(), receiver.kind(), Arc::clone(&self.dtls_transport), Arc::clone(&self.media_engine), interceptor, )); t.set_receiver(receiver).await; } } self.start_rtp_receivers(&mut track_details, ¤t_transceivers, is_renegotiation) .await?; if let Some(parsed_remote) = &remote_desc.parsed { let current_local_desc = self.current_local_description.lock().await; if let Some(parsed_local) = current_local_desc .as_ref() .and_then(|desc| desc.parsed.as_ref()) { if let Some(remote_port) = get_application_media_section_sctp_port(parsed_remote) { if let Some(local_port) = get_application_media_section_sctp_port(parsed_local) { // TODO: Reuse the MediaDescription retrieved when looking for the message size. let max_message_size = get_application_media_section_max_message_size(parsed_remote) .unwrap_or(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE); self.start_sctp( local_port, remote_port, SCTPTransportCapabilities { max_message_size }, ) ``` -------------------------------- ### Option::iter_mut Example Source: https://docs.rs/webrtc/0.17.1/webrtc/rtp_transceiver/type.TriggerNegotiationNeededFnOption.html Shows how to get a mutable iterator over the contained value of an Option. ```rust let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); let mut x: Option = None; assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### fn start_send(self: Pin<&mut Box>, item: Item) -> Result<(), as Sink>::Error> Source: https://docs.rs/webrtc/0.17.1/webrtc/error/type.OnErrorHdlrFn.html?search=u32+-%3E+bool Starts the process of sending an item into the sink. ```APIDOC ## fn start_send(self: Pin<&mut Box>, item: Item) -> Result<(), as Sink>::Error> ### Description Starts the process of sending an item into the sink. ### Type Parameters * `Item`: The type of the item to send. ### Parameters * `self`: A pinned mutable reference to the `Box`. * `item` (Item): The item to send. ### Returns * `Result<(), as Sink>::Error>`: Ok if the item was accepted for sending, or an error if sending failed immediately. ``` -------------------------------- ### Start RTP Senders and Enqueue Operation Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/mod.rs.html?search=std%3A%3Avec Initiates RTP senders and enqueues an asynchronous operation to start RTP, passing necessary context like the local description status and remote description. This is part of the session setup process. ```rust self.start_rtp_senders().await?; let pci = Arc::clone(&self.internal); let remote_desc = Arc::new(remote_desc); self.internal .ops .enqueue(Operation::new( move || { let pc = Arc::clone(&pci); let rd = Arc::clone(&remote_desc); Box::pin(async move { let _ = pc.start_rtp(have_local_description, rd).await; false }) }, "set_local_description", )) .await?; ``` -------------------------------- ### Populate SDP Parameters Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/peer_connection_internal.rs.html?search=u32+-%3E+bool Sets up parameters for populating the SDP, including media description fingerprint, ICE lite status, and connection role. This is used when generating SDP offers or answers. ```rust let params = PopulateSdpParams { media_description_fingerprint: self.setting_engine.sdp_media_level_fingerprints, is_icelite: self.setting_engine.candidates.ice_lite, extmap_allow_mixed: true, connection_role: DEFAULT_DTLS_ROLE_OFFER.to_connection_role(), ice_gathering_state: self.ice_gathering_state(), match_bundle_group: None, }; populate_sdp( d, &dtls_fingerprints, &self.media_engine, &candidates, &ice_params, &media_sections, params, ) .await ``` -------------------------------- ### RTCRtpReceiver State Management Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search= Provides methods to manage the state of the RTP receiver, including getting the current state, starting, pausing, resuming, and closing the receiver. ```APIDOC ## State Management ### current_state #### Description Gets the current state of the RTP receiver. #### Method `fn current_state(&self) -> State` ### start #### Description Transitions the RTP receiver to the `Started` state. #### Method `fn start(&self) -> Result<()>` ### pause #### Description Transitions the RTP receiver to a paused state. If the receiver is `Unstarted`, it transitions to `UnstartedPaused`. If it is `Started`, it transitions to `Paused`. #### Method `fn pause(&self) -> Result<()>` ### resume #### Description Resumes the RTP receiver. If the receiver was `UnstartedPaused`, it transitions to `Unstarted`. If it was `Paused`, it transitions to `Started`. #### Method `fn resume(&self) -> Result<()>` ### close #### Description Transitions the RTP receiver to the `Stopped` state. #### Method `fn close(&self) -> Result<()>` ``` -------------------------------- ### ICE Server Configuration and Error Handling Source: https://docs.rs/webrtc/0.17.1/src/webrtc/ice_transport/ice_server.rs.html?search= Demonstrates how to configure ICE servers with URLs, usernames, and credentials, and how to handle potential errors during STUN queries. ```rust urls: vec!["stun:google.de?transport=udp".to_owned()], username: "unittest".to_owned(), credential: String::new(), }, ice::Error::ErrStunQuery, )]; for (ice_server, expected_err) in tests { if let Err(err) = ice_server.urls() { assert_eq!(err, expected_err, "{ice_server:?} with err {err:?}"); } else { panic!("expected error, but got ok"); } } } ``` -------------------------------- ### RTPReceiver State Transitions Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides methods to manage the state of the RTPReceiver, including getting the current state, starting, pausing, resuming, and closing the receiver. These methods facilitate controlled lifecycle management. ```rust /// Get the current state and a receiver for the next state change. pub(crate) fn current_state(&self) -> State { *self.state_rx.borrow() } pub(crate) fn start(&self) -> Result<()> { State::transition(State::Started, &self.state_tx) } pub(crate) fn pause(&self) -> Result<()> { let current = self.current_state(); match current { State::Unstarted => State::transition(State::UnstartedPaused, &self.state_tx), State::Started => State::transition(State::Paused, &self.state_tx), _ => Ok(()), } } pub(crate) fn resume(&self) -> Result<()> { let current = self.current_state(); match current { State::UnstartedPaused => State::transition(State::Unstarted, &self.state_tx), State::Paused => State::transition(State::Started, &self.state_tx), _ => Ok(()), } } pub(crate) fn close(&self) -> Result<()> { State::transition(State::Stopped, &self.state_tx) } ``` -------------------------------- ### Create Answer Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/struct.RTCPeerConnection.html Starts the PeerConnection and generates the local Session Description (answer). ```rust pub async fn create_answer( &self, _options: Option, ) -> Result ``` -------------------------------- ### RTPReceiver Is Started Check Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=std%3A%3Avec Determines if the RTPReceiver is in a 'started' state, which includes both `Started` and `Paused` states. ```rust fn is_started(&self) -> bool { matches!(self, Self::Started | Self::Paused) } ``` -------------------------------- ### Mux::new Source: https://docs.rs/webrtc/0.17.1/webrtc/mux/struct.Mux.html Initializes a new Mux with the provided configuration. ```APIDOC ## Mux::new ### Description Initializes a new Mux with the provided configuration. ### Signature ```rust pub fn new(config: Config) -> Self ``` ``` -------------------------------- ### RTPReceiver Check if Started Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=u32+-%3E+bool A simple boolean check to determine if the RTPReceiver is in a 'started' state, which includes both `Started` and `Paused` states. ```rust fn is_started(&self) -> bool { matches!(self, Self::Started | Self::Paused) } } ``` -------------------------------- ### Create and Test Offer Session Description Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/sdp/session_description.rs.html Demonstrates creating an offer session description and verifying its type and parsed content. ```rust #[tokio::test] async fn test_session_description_offer() -> Result<()> { let mut m = MediaEngine::default(); m.register_default_codecs()?; let api = APIBuilder::new().with_media_engine(m).build(); let pc = api.new_peer_connection(RTCConfiguration::default()).await?; let offer = pc.create_offer(None).await?; let desc = RTCSessionDescription::offer(offer.sdp.clone())?; assert!(desc.sdp_type == RTCSdpType::Offer); assert!(desc.parsed.is_some()); assert_eq!(offer.unmarshal()?.marshal(), desc.unmarshal()?.marshal()); Ok(()) } ``` -------------------------------- ### Check if Receiver has Started Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=std%3A%3Avec Checks if the RTPReceiver has started receiving data by querying its internal state. Returns true if the state is 'started'. ```rust pub(crate) async fn have_received(&self) -> bool { self.internal.current_state().is_started() } ``` -------------------------------- ### Get SettingEngine Source: https://docs.rs/webrtc/0.17.1/src/webrtc/api/mod.rs.html?search= Returns a clone of the internal SettingEngine. ```rust pub fn setting_engine(&self) -> Arc { Arc::clone(&self.setting_engine) } ``` -------------------------------- ### Box::from_raw Example Source: https://docs.rs/webrtc/0.17.1/webrtc/data_channel/type.OnCloseHdlrFn.html Demonstrates how to recreate a Box from a raw pointer obtained using Box::into_raw. This is crucial for managing memory and ensuring proper cleanup. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### Writing Media Samples with Audio Level Source: https://docs.rs/webrtc/0.17.1/src/webrtc/track/track_local/track_local_static_sample.rs.html?search= Demonstrates how to create a TrackLocalStaticSample and write a media sample with an audio level extension. Requires setting up a codec capability and track details. ```rust use rtp::extension::audio_level_extension::AudioLevelExtension; use std::time::Duration; use webrtc::api::media_engine::MIME_TYPE_VP8; use webrtc::rtp_transceiver::rtp_codec::RTCRtpCodecCapability; use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample; #[tokio::main] async fn main() { let track = TrackLocalStaticSample::new( RTCRtpCodecCapability { mime_type: MIME_TYPE_VP8.to_owned(), ..Default::default() }, "video".to_owned(), "webrtc-rs".to_owned(), ); let result = track .sample_writer() .with_audio_level(AudioLevelExtension { level: 10, voice: true, }) .write_sample(&media::Sample{ data: bytes::Bytes::new(), duration: Duration::from_secs(1), ..Default::default() }) .await; } ``` -------------------------------- ### RTCRtpCapabilities Search Examples Source: https://docs.rs/webrtc/0.17.1/webrtc/rtp_transceiver/struct.RTCRtpCapabilities.html?search= Examples of how to search for RTCRtpCapabilities. ```APIDOC ## Search Examples Example searches: * `std::vec` * `u32 -> bool` * `Option, (T -> U) -> Option` ``` -------------------------------- ### Option::or Example Source: https://docs.rs/webrtc/0.17.1/webrtc/rtp_transceiver/type.TriggerNegotiationNeededFnOption.html Illustrates providing a default Option value if the original Option is None. ```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); ``` -------------------------------- ### API Search Examples Source: https://docs.rs/webrtc/0.17.1/webrtc/api/struct.API.html?search= Examples of how to perform searches within the API. ```APIDOC ## API Search This section provides examples of search queries that can be used with the API. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Try Get Function (128-bit) Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnSignalingStateChangeHdlrFn.html?search= Function to safely get an unsigned 128-bit integer. ```APIDOC ## Try Get Function (128-bit) ### `try_get_u128() -> Result` Gets an unsigned 128 bit integer from `self` in big-endian byte order. ``` -------------------------------- ### ICE Server Configuration Example Source: https://docs.rs/webrtc/0.17.1/src/webrtc/ice_transport/ice_server.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the configuration of an ICE server with a STUN URL, username, and an empty credential. This is typically used for testing or specific network configurations. ```rust urls: vec!["stun:google.de?transport=udp".to_owned()], username: "unittest".to_owned(), credential: String::new(), ``` -------------------------------- ### RTCRtpReceiver::receive Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=std%3A%3Avec Initializes the track and starts all the transports. Returns an error if the receiver has already been started. ```APIDOC ## receive ### Description Initialize the track and starts all the transports ### Method `receive(&self, parameters: &RTCRtpReceiveParameters) -> Result<()>` ### Parameters #### Path Parameters - **parameters** (*RTCRtpReceiveParameters*) - The parameters for receiving RTP. ### Errors - `Error::ErrRTPReceiverReceiveAlreadyCalled`: If the receiver has already been started. ``` -------------------------------- ### Box::from_non_null Example: Manual Allocation Source: https://docs.rs/webrtc/0.17.1/webrtc/error/type.OnErrorHdlrFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a `Box` from scratch using the global allocator and a `NonNull` pointer. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()).expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Create and Set WebRTC Answer Session Description Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/sdp/session_description.rs.html?search= Sets up two peer connections, creates an offer from one, sets it as the remote description on the other, and then creates an answer. It then constructs an RTCSessionDescription of type 'Answer' from the answer SDP and verifies its properties. ```rust let mut m = MediaEngine::default(); m.register_default_codecs()?; let api = APIBuilder::new().with_media_engine(m).build(); let offer_pc = api.new_peer_connection(RTCConfiguration::default()).await?; let answer_pc = api.new_peer_connection(RTCConfiguration::default()).await?; let _ = offer_pc.create_data_channel("foo", None).await?; let offer = offer_pc.create_offer(None).await?; answer_pc.set_remote_description(offer).await?; let answer = answer_pc.create_answer(None).await?; let desc = RTCSessionDescription::answer(answer.sdp.clone())?; assert!(desc.sdp_type == RTCSdpType::Answer); assert!(desc.parsed.is_some()); assert_eq!(answer.unmarshal()?.marshal(), desc.unmarshal()?.marshal()); ``` -------------------------------- ### Try Get Functions (8-bit) Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnSignalingStateChangeHdlrFn.html?search= Functions to safely get signed and unsigned 8-bit integers. ```APIDOC ## Try Get Functions (8-bit) ### `try_get_u8() -> Result` Gets an unsigned 8 bit integer from `self`. ### `try_get_i8() -> Result` Gets a signed 8 bit integer from `self`. ``` -------------------------------- ### Try Get 128-bit Integer Functions Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnDataChannelHdlrFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Function to safely get an unsigned 128-bit integer. ```APIDOC ## try_get_u128(&mut self) -> Result ### Description Gets an unsigned 128 bit integer from `self` in big-endian byte order. ### Method `try_get_u128` ### Response #### Success Response (Result) - Returns Ok(u128) containing the unsigned 128-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` -------------------------------- ### start Source: https://docs.rs/webrtc/0.17.1/webrtc/ice_transport/struct.RTCIceTransport.html Initiates ICE connectivity checks based on the configured role and provided ICE parameters. ```APIDOC ## start ### Description Start incoming connectivity checks based on its configured role. ### Method POST (implied) ### Endpoint N/A (Method on struct) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (RTCIceParameters) - Required - The ICE parameters to use for starting. - **role** (Option) - Optional - The role for the ICE transport. ``` -------------------------------- ### Start RTP Senders Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/mod.rs.html Starts all outbound RTP streams for negotiated tracks that have not yet sent data. ```rust pub(crate) async fn start_rtp_senders(&self) -> Result<()> { let current_transceivers = self.internal.rtp_transceivers.lock().await; for transceiver in &*current_transceivers { let sender = transceiver.sender().await; if !sender.track_encodings.lock().await.is_empty() && sender.is_negotiated() && !sender.has_sent() { sender.send(&sender.get_parameters().await).await?; } } Ok(()) } ``` -------------------------------- ### create_offer Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/mod.rs.html?search=u32+-%3E+bool Initiates the PeerConnection and generates the local description (SDP offer). Handles ICE restart if specified in options. ```APIDOC ## create_offer ### Description Starts the PeerConnection and generates the localDescription (SDP offer). This method handles ICE restart if the `ice_restart` option is set. It may recompute the offer if transceivers are modified during the process. ### Method `create_offer(&self, options: Option) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example of calling create_offer with optional options let offer_options = RTCOfferOptions { ice_restart: true, ... }; let offer = peer_connection.create_offer(Some(offer_options)).await?; ``` ### Response #### Success Response (Result) - **RTCSessionDescription**: An object representing the generated SDP offer. #### Response Example ```json { "sdp": "v=0...", "type": "offer" } ``` ``` -------------------------------- ### Try Get Single Byte Functions Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnDataChannelHdlrFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions to safely get single unsigned and signed bytes. ```APIDOC ## try_get_u8(&mut self) -> Result ### Description Gets an unsigned 8 bit integer from `self`. ### Method `try_get_u8` ### Response #### Success Response (Result) - Returns Ok(u8) containing the unsigned 8-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i8(&mut self) -> Result ### Description Gets a signed 8 bit integer from `self`. ### Method `try_get_i8` ### Response #### Success Response (Result) - Returns Ok(i8) containing the signed 8-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` -------------------------------- ### Write Sample with RTP Extensions Source: https://docs.rs/webrtc/0.17.1/src/webrtc/track/track_local/track_local_static_sample.rs.html Writes a media Sample with provided RTP extensions. This method can also be used via the `sample_writer`. ```rust pub async fn write_sample_with_extensions( &self, sample: &Sample, extensions: &[rtp::extension::HeaderExtension], ) -> Result<()> { let mut internal = self.internal.lock().await; if internal.packetizer.is_none() || internal.sequencer.is_none() { return Ok(()); } let (any_paused, all_paused) = ( self.rtp_track.any_binding_paused().await, self.rtp_track.all_binding_paused().await, ); if all_paused { // Abort already here to not increment sequence numbers. return Ok(()); } if any_paused { // This is a problem state due to how this impl is structured. The sequencer will allocate // one sequence number per RTP packet regardless of how many TrackBinding that will send // the packet. I.e. we get the same sequence number per multiple SSRC, which is not good // for SRTP, but that's how it works. // // SRTP has a further problem with regards to jumps in sequence number. Consider this: // // 1. Create track local // 2. Bind track local to track 1. // 3. Bind track local to track 2. // 4. Pause track 1. // 5. Keep sending... // // At this point, the track local will keep incrementing the sequence number, because we have // one binding that is still active. However SRTP hmac verifying (tag), can only accept a // relatively small jump in sequence numbers since it uses the ROC (i.e. how many times the // sequence number has rolled over), which means if this pause state of one binding persists ``` -------------------------------- ### Option IntoIterator Example Source: https://docs.rs/webrtc/0.17.1/webrtc/rtp_transceiver/type.TriggerNegotiationNeededFnOption.html Demonstrates how to use `into_iter` to convert an `Option` into an iterator. The first example shows iteration over a `Some` variant, collecting its value into a `Vec`. The second example shows iteration over a `None` variant, resulting in an empty `Vec`. ```rust let x = Some("string"); let v: Vec<&str> = x.into_iter().collect(); assert_eq!(v, ["string"]); let x = None; let v: Vec<&str> = x.into_iter().collect(); assert!(v.is_empty()); ``` -------------------------------- ### Create WebRTC Offer Session Description Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/sdp/session_description.rs.html?search= Creates a new peer connection, generates an offer, and then constructs an RTCSessionDescription of type 'Offer' from the offer SDP. It asserts the SDP type and checks if the SDP has been parsed. ```rust let mut m = MediaEngine::default(); m.register_default_codecs()?; let api = APIBuilder::new().with_media_engine(m).build(); let pc = api.new_peer_connection(RTCConfiguration::default()).await?; let offer = pc.create_offer(None).await?; let desc = RTCSessionDescription::offer(offer.sdp.clone())?; assert!(desc.sdp_type == RTCSdpType::Offer); assert!(desc.parsed.is_some()); assert_eq!(offer.unmarshal()?.marshal(), desc.unmarshal()?.marshal()); ``` -------------------------------- ### Start RTP Receiver - Rust Source: https://docs.rs/webrtc/0.17.1/src/webrtc/rtp_transceiver/rtp_receiver/mod.rs.html?search=u32+-%3E+bool Transitions the RTP receiver state to 'Started'. Returns an error if the transition is invalid. ```rust pub(crate) fn start(&self) -> Result<()> { State::transition(State::Started, &self.state_tx) } ``` -------------------------------- ### Start Receiver for Incoming RTP Stream Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/peer_connection_internal.rs.html?search=std%3A%3Avec Starts the receiver for an incoming RTP stream, processing it with the provided handler. ```rust let receiver = t.receiver().await; PeerConnectionInternal::start_receiver( self.setting_engine.get_receive_mtu(), &incoming, receiver, t, Arc::clone(&self.on_track_handler), ) .await; ``` -------------------------------- ### setting_engine Source: https://docs.rs/webrtc/0.17.1/src/webrtc/api/mod.rs.html?search=u32+-%3E+bool Returns a clone of the internal SettingEngine. ```APIDOC ## setting_engine ### Description Returns the internal [`SettingEngine`]. ### Method Signature `pub fn setting_engine(&self) -> Arc` ``` -------------------------------- ### Initialize Session Description for Matching Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/peer_connection_internal.rs.html?search=std%3A%3Avec Creates a new JSEP session description, which is the base for generating SDP when matching remote descriptions. ```rust let d = SessionDescription::new_jsep_session_description(use_identity); ``` -------------------------------- ### Try Get Functions (64-bit) Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnSignalingStateChangeHdlrFn.html?search= Functions to safely get signed and unsigned 64-bit integers with endianness options. ```APIDOC ## Try Get Functions (64-bit) ### `try_get_u64() -> Result` Gets an unsigned 64 bit integer from `self` in big-endian byte order. ### `try_get_u64_le() -> Result` Gets an unsigned 64 bit integer from `self` in little-endian byte order. ### `try_get_u64_ne() -> Result` Gets an unsigned 64 bit integer from `self` in native-endian byte order. ### `try_get_i64() -> Result` Gets a signed 64 bit integer from `self` in big-endian byte order. ### `try_get_i64_le() -> Result` Gets a signed 64 bit integer from `self` in little-endian byte order. ### `try_get_i64_ne() -> Result` Gets a signed 64 bit integer from `self` in native-endian byte order. ``` -------------------------------- ### Try Get Functions (32-bit) Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnSignalingStateChangeHdlrFn.html?search= Functions to safely get signed and unsigned 32-bit integers with endianness options. ```APIDOC ## Try Get Functions (32-bit) ### `try_get_u32() -> Result` Gets an unsigned 32 bit integer from `self` in big-endian byte order. ### `try_get_u32_le() -> Result` Gets an unsigned 32 bit integer from `self` in little-endian byte order. ### `try_get_u32_ne() -> Result` Gets an unsigned 32 bit integer from `self` in native-endian byte order. ### `try_get_i32() -> Result` Gets a signed 32 bit integer from `self` in big-endian byte order. ### `try_get_i32_le() -> Result` Gets a signed 32 bit integer from `self` in little-endian byte order. ### `try_get_i32_ne() -> Result` Gets a signed 32 bit integer from `self` in native-endian byte order. ``` -------------------------------- ### create_offer Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/mod.rs.html?search= Initiates the PeerConnection and generates the local description (offer). This is a key step in establishing a WebRTC connection. ```APIDOC ## create_offer ### Description Starts the PeerConnection process and generates the local description (an offer) to be sent to the remote peer. This method is crucial for initiating a WebRTC call. ### Method `create_offer(options?: RTCOfferOptions)` ### Endpoint N/A (SDK method) ### Parameters #### Query Parameters - **options** (RTCOfferOptions) - Optional. Configuration options for creating the offer, such as `iceRestart`. ### Request Example ```javascript // Example with options const offerOptions = { iceRestart: true }; const offer = await peerConnection.create_offer(offerOptions); // Example without options // const offer = await peerConnection.create_offer(); ``` ### Response #### Success Response (200) - **RTCSessionDescription** (object) - The generated local session description (offer). #### Error Response - **ErrIdentityProviderNotImplemented** - If identity provider features are not implemented. - **ErrConnectionClosed** - If the connection is already closed. ### Response Example ```json { "type": "offer", "sdp": "v=0\r\no=- 1234567890 1234567890 IN IP4 127.0.0.1\r\ns=MyStream\r\n..." } ``` ``` -------------------------------- ### Try Get Functions (16-bit) Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnSignalingStateChangeHdlrFn.html?search= Functions to safely get signed and unsigned 16-bit integers with endianness options. ```APIDOC ## Try Get Functions (16-bit) ### `try_get_u16() -> Result` Gets an unsigned 16 bit integer from `self` in big-endian byte order. ### `try_get_u16_le() -> Result` Gets an unsigned 16 bit integer from `self` in little-endian byte order. ### `try_get_u16_ne() -> Result` Gets an unsigned 16 bit integer from `self` in native-endian byte order. ### `try_get_i16() -> Result` Gets a signed 16 bit integer from `self` in big-endian byte order. ### `try_get_i16_le() -> Result` Gets an signed 16 bit integer from `self` in little-endian byte order. ### `try_get_i16_ne() -> Result` Gets a signed 16 bit integer from `self` in native-endian byte order. ``` -------------------------------- ### Create and Test Offer Session Description Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/sdp/session_description.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates an offer for a WebRTC session and verifies its properties. This is typically the first step in establishing a WebRTC connection. ```rust #[tokio::test] async fn test_session_description_offer() -> Result<()> { let mut m = MediaEngine::default(); m.register_default_codecs()?; let api = APIBuilder::new().with_media_engine(m).build(); let pc = api.new_peer_connection(RTCConfiguration::default()).await?; let offer = pc.create_offer(None).await?; let desc = RTCSessionDescription::offer(offer.sdp.clone())?; assert!(desc.sdp_type == RTCSdpType::Offer); assert!(desc.parsed.is_some()); assert_eq!(offer.unmarshal()?.marshal(), desc.unmarshal()?.marshal()); Ok(()) } ``` -------------------------------- ### Populate SDP Session Description Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/sdp/mod.rs.html?search= Asynchronously populates a SessionDescription with DTLS fingerprints, ICE candidates, and media sections based on provided parameters and media engine information. ```rust /// populate_sdp serializes a PeerConnections state into an SDP pub(crate) async fn populate_sdp( mut d: SessionDescription, dtls_fingerprints: &[RTCDtlsFingerprint], media_engine: &Arc, candidates: &[RTCIceCandidate], ice_params: &RTCIceParameters, media_sections: &[MediaSection], params: PopulateSdpParams, ) -> Result { let media_dtls_fingerprints = if params.media_description_fingerprint { dtls_fingerprints.to_vec() } else { vec![] }; let mut bundle_value = "BUNDLE".to_owned(); let mut bundle_count = 0; let append_bundle = |mid_value: &str, value: &mut String, count: &mut i32| { *value = value.clone() + " " + mid_value; *count += 1; }; for (i, m) in media_sections.iter().enumerate() { if m.data && !m.transceivers.is_empty() { return Err(Error::ErrSDPMediaSectionMediaDataChanInvalid); } else if m.transceivers.len() > 1 { return Err(Error::ErrSDPMediaSectionMultipleTrackInvalid); } let should_add_candidates = i == 0; let should_add_id = if m.data { let params = AddDataMediaSectionParams { should_add_candidates, mid_value: m.id.clone(), ice_params: ice_params.clone(), dtls_role: params.connection_role, ice_gathering_state: params.ice_gathering_state, }; d = add_data_media_section(d, &media_dtls_fingerprints, candidates, params).await?; true } else { let params = AddTransceiverSdpParams { should_add_candidates, mid_value: m.id.clone(), dtls_role: params.connection_role, ice_gathering_state: params.ice_gathering_state, offered_direction: m.offered_direction, }; let (d1, should_add_id) = add_transceiver_sdp( d, ``` -------------------------------- ### Start Transports and RTP Source: https://docs.rs/webrtc/0.17.1/src/webrtc/peer_connection/mod.rs.html Initiates WebRTC transports and starts RTP streams. This is typically called after setting the remote description. ```rust let dtls_role = DTLSRole::from(parsed); let remote_desc = Arc::new(desc); self.internal .ops .enqueue(Operation::new( move || { let pc = Arc::clone(&pci); let rd = Arc::clone(&remote_desc); let ru = remote_ufrag.clone(); let rp = remote_pwd.clone(); let fp = fingerprint.clone(); let fp_hash = fingerprint_hash.clone(); Box::pin(async move { log::trace!( "start_transports: ice_role={ice_role}, dtls_role={dtls_role}", ); pc.start_transports(ice_role, dtls_role, ru, rp, fp, fp_hash) .await; if we_offer { let _ = pc.start_rtp(false, rd).await; } false }) }, "set_remote_description", )) .await?; ``` -------------------------------- ### Box::into_raw Example Source: https://docs.rs/webrtc/0.17.1/webrtc/data_channel/type.OnCloseHdlrFn.html Shows how to consume a Box and obtain a raw pointer to the contained data. The caller then becomes responsible for managing the memory. ```rust let x = Box::new(String::from("Hello")); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` -------------------------------- ### start Source: https://docs.rs/webrtc/0.17.1/src/webrtc/dtls_transport/mod.rs.html?search=std%3A%3Avec Starts the DTLS transport negotiation with the parameters of the remote DTLS transport. This method initiates the DTLS handshake process. ```APIDOC ## start ### Description Starts the DTLS transport negotiation with the parameters of the remote DTLS transport. ### Method `pub async fn start(&self, remote_parameters: DTLSParameters) -> Result<()>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **remote_parameters** (DTLSParameters) - The DTLS parameters of the remote DTLS transport. ### Request Example ```rust // Assuming `dtls_transport` is an instance of the DTLS transport and `remote_params` is a DTLSParameters object let result = dtls_transport.start(remote_params).await; match result { Ok(_) => println!("DTLS transport started successfully."), Err(e) => eprintln!("Failed to start DTLS transport: {}", e), } ``` ### Response #### Success Response (200) Returns `Ok(())` if the DTLS transport negotiation is initiated successfully. #### Response Example ```json null ``` ### Error Handling Returns an `Err` if the DTLS transport cannot be started, for example, if the ICE transport is not ready or if there are issues with certificates. ``` -------------------------------- ### Box::from_raw Example Source: https://docs.rs/webrtc/0.17.1/webrtc/data_channel/type.OnOpenHdlrFn.html?search=u32+-%3E+bool Demonstrates how to recreate a Box from a raw pointer. This is useful for taking ownership of memory that was previously converted to a raw pointer using `Box::into_raw`. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Try Get 64-bit Integer Functions Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnDataChannelHdlrFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions to safely get unsigned and signed 64-bit integers with endianness options. ```APIDOC ## try_get_u64(&mut self) -> Result ### Description Gets an unsigned 64 bit integer from `self` in big-endian byte order. ### Method `try_get_u64` ### Response #### Success Response (Result) - Returns Ok(u64) containing the unsigned 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_u64_le(&mut self) -> Result ### Description Gets an unsigned 64 bit integer from `self` in little-endian byte order. ### Method `try_get_u64_le` ### Response #### Success Response (Result) - Returns Ok(u64) containing the unsigned 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_u64_ne(&mut self) -> Result ### Description Gets an unsigned 64 bit integer from `self` in native-endian byte order. ### Method `try_get_u64_ne` ### Response #### Success Response (Result) - Returns Ok(u64) containing the unsigned 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i64(&mut self) -> Result ### Description Gets a signed 64 bit integer from `self` in big-endian byte order. ### Method `try_get_i64` ### Response #### Success Response (Result) - Returns Ok(i64) containing the signed 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i64_le(&mut self) -> Result ### Description Gets a signed 64 bit integer from `self` in little-endian byte order. ### Method `try_get_i64_le` ### Response #### Success Response (Result) - Returns Ok(i64) containing the signed 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i64_ne(&mut self) -> Result ### Description Gets a signed 64 bit integer from `self` in native-endian byte order. ### Method `try_get_i64_ne` ### Response #### Success Response (Result) - Returns Ok(i64) containing the signed 64-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` -------------------------------- ### Try Get 32-bit Integer Functions Source: https://docs.rs/webrtc/0.17.1/webrtc/peer_connection/type.OnDataChannelHdlrFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Functions to safely get unsigned and signed 32-bit integers with endianness options. ```APIDOC ## try_get_u32(&mut self) -> Result ### Description Gets an unsigned 32 bit integer from `self` in big-endian byte order. ### Method `try_get_u32` ### Response #### Success Response (Result) - Returns Ok(u32) containing the unsigned 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_u32_le(&mut self) -> Result ### Description Gets an unsigned 32 bit integer from `self` in little-endian byte order. ### Method `try_get_u32_le` ### Response #### Success Response (Result) - Returns Ok(u32) containing the unsigned 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_u32_ne(&mut self) -> Result ### Description Gets an unsigned 32 bit integer from `self` in native-endian byte order. ### Method `try_get_u32_ne` ### Response #### Success Response (Result) - Returns Ok(u32) containing the unsigned 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i32(&mut self) -> Result ### Description Gets a signed 32 bit integer from `self` in big-endian byte order. ### Method `try_get_i32` ### Response #### Success Response (Result) - Returns Ok(i32) containing the signed 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i32_le(&mut self) -> Result ### Description Gets a signed 32 bit integer from `self` in little-endian byte order. ### Method `try_get_i32_le` ### Response #### Success Response (Result) - Returns Ok(i32) containing the signed 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` ```APIDOC ## try_get_i32_ne(&mut self) -> Result ### Description Gets a signed 32 bit integer from `self` in native-endian byte order. ### Method `try_get_i32_ne` ### Response #### Success Response (Result) - Returns Ok(i32) containing the signed 32-bit integer if successful. #### Error Response (TryGetError) - Returns TryGetError if there are not enough bytes. ``` -------------------------------- ### Box::from_non_null Example: Manual Allocation with NonNull Source: https://docs.rs/webrtc/0.17.1/webrtc/data_channel/type.OnMessageHdlrFn.html?search= Demonstrates manual creation of a `Box` using a `NonNull` pointer obtained from the global allocator. This is an experimental nightly-only feature. ```rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### API Builder WithSettingEngine Source: https://docs.rs/webrtc/0.17.1/src/webrtc/api/mod.rs.html?search= Provides a SettingEngine to the API builder. Settings should not be changed after this. ```rust pub fn with_setting_engine(mut self, setting_engine: SettingEngine) -> Self { self.setting_engine = Some(Arc::new(setting_engine)); self } ```