### Run ice-restart Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/ice-restart/README.md Execute this command to run the ice-restart example. This will start a WebRTC peer connection. ```shell cargo run --example ice-restart ``` -------------------------------- ### Run Data Channels Offer Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-offer-answer/README.md Execute this command to start the data channels offerer. It will connect to the answerer and exchange messages. ```shell cargo run --example data-channels-offer ``` -------------------------------- ### Build the Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-renegotiation/README.md Compiles the play-from-disk-renegotiation example using Cargo. Ensure you are in the project root directory. ```shell cargo build --example play-from-disk-renegotiation ``` -------------------------------- ### Build data-channels-create Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-create/README.md Use this command to compile the data-channels-create example application. ```shell cargo build --example data-channels-create ``` -------------------------------- ### Build ice-restart Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/ice-restart/README.md Use this command to build the ice-restart example. Ensure you are in the project directory. ```shell cargo build --example ice-restart ``` -------------------------------- ### Build the play-from-disk-vpx Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Compile the play-from-disk-vpx example using Cargo. This prepares the executable for running. ```shell cargo build --example play-from-disk-vpx ``` -------------------------------- ### Build save-to-disk-h26x Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-h26x/README.md Build the save-to-disk-h26x example using Cargo. This command compiles the example application, making it ready to run. ```shell cargo build --example save-to-disk-h26x ``` -------------------------------- ### Build save-to-disk-vpx Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-vpx/README.md Build the save-to-disk-vpx example using Cargo. This command compiles the example application, making it ready to run. ```shell cargo build --example save-to-disk-vpx ``` -------------------------------- ### Build the Reflect Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/reflect/README.md Compiles the reflect example using Cargo. Ensure you have Rust and Cargo installed. ```shell cargo build --example reflect ``` -------------------------------- ### Run Data Channels Answer Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-offer-answer/README.md Execute this command to start the data channels answerer, which acts as an HTTP server for SDP exchange. This must be run first. ```shell cargo run --example data-channels-answer ``` -------------------------------- ### Build Broadcast Application Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/broadcast/README.md Use this command to compile the broadcast example. Ensure you have Rust and Cargo installed. ```shell cargo build --example broadcast ``` -------------------------------- ### Run Reflect Example (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/reflect/README.md Executes the reflect example, piping the browser's SessionDescription from the BROWSER_SDP environment variable. ```shell echo $BROWSER_SDP | ./target/debug/examples/reflect -a -v ``` -------------------------------- ### Run Insertable Streams Example (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/insertable-streams/README.md Execute the compiled insertable-streams example on Windows by redirecting session description from a file. ```shell ./target/debug/examples/insertable-streams < my_file ``` -------------------------------- ### Build rtp-to-webrtc Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-to-webrtc/README.md Builds the rtp-to-webrtc example using Cargo. This command is used to compile the example for local execution. ```shell cargo build --example rtp-to-webrtc ``` -------------------------------- ### Build swap-tracks Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/swap-tracks/README.md Build the swap-tracks example using Cargo. This command compiles the Rust code for the example. ```shell cargo build --example swap-tracks ``` -------------------------------- ### Run Reflect Example (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/reflect/README.md Executes the reflect example on Windows by reading the browser's SessionDescription from a file. ```shell ./target/debug/examples/reflect -a -v < my_file ``` -------------------------------- ### Run WebRTC DataChannel Example Server Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-simple/README.md Execute the Rust server for the WebRTC DataChannel example. This example requires the default Tokio runtime. ```bash cargo run --example data-channels-simple ``` -------------------------------- ### Run Insertable Streams Example (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/insertable-streams/README.md Execute the compiled insertable-streams example on Linux or macOS, piping the browser's Session Description Protocol (SDP) as standard input. ```shell echo $BROWSER_SDP | ./target/debug/examples/insertable-streams ``` -------------------------------- ### Build Simulcast Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/simulcast_add_transceiver_from_kind/README.md Build the simulcast example using Cargo. This command compiles the Rust code for the simulcast example. ```shell cargo build --example simulcast ``` -------------------------------- ### Run save-to-disk-h26x on Linux/macOS Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-h26x/README.md Execute the save-to-disk-h26x example on Linux or macOS by piping the browser's Session Description from stdin. Ensure the BROWSER_SDP environment variable is set. ```shell echo $BROWSER_SDP | ./target/debug/examples/save-to-disk-h26x ``` -------------------------------- ### Build Insertable Streams Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/insertable-streams/README.md Compile the insertable-streams Rust example using Cargo. ```shell cargo build --example insertable-streams ``` -------------------------------- ### Running the Data Channels Flow Control Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-flow-control/README.md This command executes the example code, demonstrating data channel throughput. Observe the output to see the measured data transfer rates. ```shell $ cargo run --release --example data-channels-flow-control Finished release [optimized] target(s) in 0.36s Running `target\release\examples\data-channels-flow-control.exe` Throughput is about 127.060 Mbps Throughput is about 122.091 Mbps Throughput is about 120.630 Mbps Throughput is about 120.105 Mbps Throughput is about 119.873 Mbps Throughput is about 118.890 Mbps Throughput is about 118.525 Mbps Throughput is about 118.614 Mbps ``` -------------------------------- ### Run save-to-disk-h26x on Windows Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-h26x/README.md Run the save-to-disk-h26x example on Windows by redirecting the browser's Session Description from a file. First, paste the Session Description into a file, then execute the command. ```shell ./target/debug/examples/save-to-disk-h26x < my_file ``` -------------------------------- ### Run swap-tracks on Linux/macOS Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/swap-tracks/README.md Execute the swap-tracks example by piping your browser's Session Description from stdin. This is used after obtaining the browser's SDP. ```shell echo $BROWSER_SDP | ./target/debug/examples/swap-tracks ``` -------------------------------- ### Run swap-tracks on Windows Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/swap-tracks/README.md Run the swap-tracks example on Windows by redirecting input from a file containing your browser's Session Description. This is an alternative to piping. ```shell ./target/debug/examples/swap-tracks < my_file ``` -------------------------------- ### Build data-channels Example Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels/README.md Build the data-channels example using Cargo. This command compiles the Rust application. ```shell cargo build --example data-channels ``` -------------------------------- ### Run play-from-disk-vpx with VP9 and Audio (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Execute the play-from-disk-vpx example on Windows, providing the browser's Session Description from a file via stdin and specifying the VP9 video and Opus audio files. Use the --vp9 flag. The '< my_file' syntax redirects file content to stdin. ```shell ./target/debug/examples/play-from-disk-vpx -v rtc/examples/examples/test-data/output_vp9.ivf -a rtc/examples/examples/test-data/output.ogg --vp9 < my_file ``` -------------------------------- ### Full Data Channel Peer Example in Rust Source: https://context7.com/webrtc-rs/webrtc/llms.txt This example sets up two peers, establishes a data channel, and exchanges messages. It requires the `webrtc` and `futures` crates. Ensure you have the necessary dependencies to run this code. ```rust use futures::FutureExt; use std::sync::Arc; use webrtc::data_channel::{DataChannel, DataChannelEvent}; use webrtc::error::Result; use webrtc::peer_connection::{ MediaEngine, PeerConnection, PeerConnectionBuilder, PeerConnectionEventHandler, RTCConfigurationBuilder, RTCIceGatheringState, RTCPeerConnectionState, Registry, register_default_interceptors, }; use webrtc::runtime::{Runtime, Sender, block_on, channel, default_runtime}; #[derive(Clone)] struct Peer { label: String, runtime: Arc, gather_tx: Sender<()> done_tx: Sender<()> } #[async_trait::async_trait] impl PeerConnectionEventHandler for Peer { async fn on_ice_gathering_state_change(&self, s: RTCIceGatheringState) { if s == RTCIceGatheringState::Complete { let _ = self.gather_tx.try_send(()); } } async fn on_connection_state_change(&self, s: RTCPeerConnectionState) { if s == RTCPeerConnectionState::Failed { let _ = self.done_tx.try_send(()); } } async fn on_data_channel(&self, dc: Arc) { let label = self.label.clone(); self.runtime.spawn(Box::pin(async move { while let Some(evt) = dc.poll().await { match evt { DataChannelEvent::OnOpen => { dc.send_text(&format!("hello from {label}")).await.ok(); } DataChannelEvent::OnMessage(msg) => { println!("[{label}] recv: {}", String::from_utf8_lossy(&msg.data)); } DataChannelEvent::OnClose => break, _ => {} } } })); } } fn build_pc( label: &str, runtime: Arc, gather_tx: Sender<()> done_tx: Sender<()> ) -> impl std::future::Future> { let handler = Arc::new(Peer { label: label.to_owned(), runtime: runtime.clone(), gather_tx, done_tx, }); let mut me = MediaEngine::default(); me.register_default_codecs().unwrap(); let reg = register_default_interceptors(Registry::new(), &mut me).unwrap(); PeerConnectionBuilder::new() .with_configuration(RTCConfigurationBuilder::new().build()) .with_media_engine(me) .with_interceptor_registry(reg) .with_handler(handler) .with_runtime(runtime) .with_udp_addrs(vec!["127.0.0.1:0".to_string()]) .build() } fn main() -> anyhow::Result<()> { block_on(async { let runtime = default_runtime().unwrap(); let (done_tx, mut done_rx) = channel::<()>(1); let (a_gather_tx, mut a_gather_rx) = channel::<()>(1); let (b_gather_tx, mut b_gather_rx) = channel::<()>(1); let pc_a = build_pc("A", runtime.clone(), a_gather_tx, done_tx.clone()).await?; let pc_b = build_pc("B", runtime.clone(), b_gather_tx, done_tx.clone()).await?; let dc = pc_a.create_data_channel("chat", None).await?; // Offer/answer let offer = pc_a.create_offer(None).await?; pc_a.set_local_description(offer.clone()).await?; pc_b.set_remote_description(offer).await?; let answer = pc_b.create_answer(None).await?; pc_b.set_local_description(answer.clone()).await?; pc_a.set_remote_description(answer).await?; // Wait for ICE gathering on both sides a_gather_rx.recv().await; b_gather_rx.recv().await; // Spawn sender on dc runtime.spawn(Box::pin(async move { while let Some(evt) = dc.poll().await { match evt { DataChannelEvent::OnOpen => { dc.send_text("ping from A").await.ok(); } DataChannelEvent::OnMessage(m) => { println!("[A] recv: {}", String::from_utf8_lossy(&m.data)); } DataChannelEvent::OnClose => break, _ => {} } } })); done_rx.recv().await; pc_a.close().await?; pc_b.close().await?; Ok(()) }) } ``` -------------------------------- ### Run play-from-disk-vpx with VP8 and Audio (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Execute the play-from-disk-vpx example, providing the browser's Session Description via stdin and specifying the VP8 video and Opus audio files. This command is for Linux and macOS environments. ```shell echo $BROWSER_SDP | ./target/debug/examples/play-from-disk-vpx -v rtc/examples/examples/test-data/output_vp8.ivf -a rtc/examples/examples/test-data/output.ogg ``` -------------------------------- ### Run play-from-disk-vpx with VP8 and Audio (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Execute the play-from-disk-vpx example on Windows, providing the browser's Session Description from a file via stdin and specifying the VP8 video and Opus audio files. The '< my_file' syntax redirects file content to stdin. ```shell ./target/debug/examples/play-from-disk-vpx -v rtc/examples/examples/test-data/output_vp8.ivf -a rtc/examples/examples/test-data/output.ogg < my_file ``` -------------------------------- ### Run Simulcast with Browser SDP (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/simulcast_add_transceiver_from_kind/README.md On Windows, save the browser's Session Description Protocol (SDP) to a file and then redirect the file's content as input to the simulcast example. This is the equivalent of piping for Windows. ```shell ./target/debug/examples/simulcast < my_file ``` -------------------------------- ### Build rtp-forwarder with Cargo Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-forwarder/README.md Build the rtp-forwarder example using the Cargo build tool. ```shell cargo build --example rtp-forwarder ``` -------------------------------- ### Build and Test webrtc-rs Source: https://github.com/webrtc-rs/webrtc/blob/master/README.md Commands to update submodules, build the library, run tests, generate documentation, and execute examples. ```bash git submodule update --init --recursive ``` ```bash cargo build ``` ```bash cargo test ``` ```bash cargo doc --open ``` ```bash cargo run --example data-channels ``` -------------------------------- ### Run rtp-to-webrtc with Browser SDP (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-to-webrtc/README.md Executes the rtp-to-webrtc example on Windows by reading the browser's Session Description Protocol (SDP) from a file. This is the command for Windows environments. ```shell ./target/debug/examples/rtp-to-webrtc < my_file ``` -------------------------------- ### Run play-from-disk-vpx with VP9 and Audio (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Execute the play-from-disk-vpx example, providing the browser's Session Description via stdin and specifying the VP9 video and Opus audio files. Use the --vp9 flag to indicate VP9 codec. This command is for Linux and macOS. ```shell echo $BROWSER_SDP | ./target/debug/examples/play-from-disk-vpx -v rtc/examples/examples/test-data/output_vp9.ivf -a rtc/examples/examples/test-data/output.ogg --vp9 ``` -------------------------------- ### Initialize WebRTC PeerConnection and DataChannel Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/ice-restart/index.html Sets up a new RTCPeerConnection with STUN servers and creates a data channel. This is the initial setup for WebRTC communication. ```javascript let pc = new RTCPeerConnection({ iceServers: [ { urls: 'stun:stun.l.google.com:19302' } ] }) let dc = pc.createDataChannel('data') ``` -------------------------------- ### Run rtp-to-webrtc with Browser SDP (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-to-webrtc/README.md Executes the rtp-to-webrtc example by piping the browser's Session Description Protocol (SDP) from stdin. This is used on Linux and macOS systems. ```shell echo $BROWSER_SDP | ./target/debug/examples/rtp-to-webrtc ``` -------------------------------- ### Run Simulcast with Browser SDP (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/simulcast_add_transceiver_from_kind/README.md Pipe the browser's Session Description Protocol (SDP) into the compiled simulcast example on Linux or macOS. This allows WebRTC.rs to establish a connection with the browser. ```shell echo $BROWSER_SDP | ./target/debug/examples/simulcast ``` -------------------------------- ### WebRTC PeerConnection Setup and Event Handling Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-renegotiation/index.html Initializes a WebRTC PeerConnection with STUN servers and sets up an 'ontrack' event handler to display incoming media streams. It also creates a no-op DataChannel to ensure the PeerConnection is not idle. ```javascript let activeVideos = 0 let pc = new RTCPeerConnection({ iceServers: [ { urls: 'stun:stun.l.google.com:19302' } ] }) pc.ontrack = function (event) { var el = document.createElement(event.track.kind) el.srcObject = event.streams[0] el.autoplay = true el.controls = true event.track.onmute = function (event) { el.parentNode.removeChild(el); } document.getElementById('remoteVideos').appendChild(el) } pc.createDataChannel('noop') ``` -------------------------------- ### Run play-from-disk-h26x with H264 Video (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-h26x/README.md Stream H264 video and Opus audio from disk to your browser by piping the browser's Session Description to the example. The video file should be in the same directory. ```shell echo $BROWSER_SDP | cargo run --example play-from-disk-h26x -- -v rtc/examples/examples/test-data/output.264 -a rtc/examples/examples/test-data/output.ogg ``` -------------------------------- ### Inspect RTP stream with ffprobe Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-forwarder/README.md Use ffprobe to get detailed information about the streams in the rtp-forwarder.sdp file. Ensure the file, UDP, and RTP protocols are whitelisted. ```shell ffprobe -i rtp-forwarder.sdp -protocol_whitelist file,udp,rtp ``` -------------------------------- ### Run play-from-disk-h26x with H265 Video (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-h26x/README.md Stream H265 video and Opus audio from disk to your browser by piping the browser's Session Description to the example. Use the --hevc flag for H265 and ensure the video file is present. ```shell echo $BROWSER_SDP | cargo run --example play-from-disk-h26x -- -v rtc/examples/examples/test-data/output.265 -a rtc/examples/examples/test-data/output.ogg --hevc ``` -------------------------------- ### Create IVF Media File Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-renegotiation/README.md Uses FFmpeg to convert an input file into an IVF format with a VP8 track, suitable for the WebRTC.rs example. The output file is named 'output.ivf'. ```shell ffmpeg -i $INPUT_FILE -g 30 output.ivf ``` -------------------------------- ### Create H264/H265 and Opus Media Files with FFmpeg Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-h26x/README.md Use FFmpeg to convert input files into H264, H265, or Opus formats suitable for WebRTC streaming. Ensure the output files are named correctly for the example. ```shell ffmpeg -i $INPUT_FILE -an -c:v libx264 -bsf:v h264_mp4toannexb -b:v 2M -max_delay 0 -bf 0 output.264 ``` ```shell ffmpeg -i $INPUT_FILE -an -c:v libx265 -bsf:v hevc_mp4toannexb -b:v 2M -max_delay 0 -bf 0 output.265 ``` ```shell ffmpeg -i $INPUT_FILE -c:a libopus -page_duration 20000 -vn output.ogg ``` -------------------------------- ### Create IVF and Ogg Media Files with ffmpeg Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-vpx/README.md Use ffmpeg to convert input files into VP8/VP9 IVF format for video and Opus Ogg format for audio. Ensure the output files are named correctly for the example. ```shell ffmpeg -i $INPUT_FILE -g 30 output_vp8.ivf ffmpeg -i $INPUT_FILE -g 30 -c libvpx-vp9 output_vp9.ivf ffmpeg -i $INPUT_FILE -map 0:a -c:a dca -ac 2 -c:a libopus -page_duration 20000 -vn output.ogg ``` -------------------------------- ### Get WebRTC Connection Statistics Source: https://context7.com/webrtc-rs/webrtc/llms.txt Retrieves a snapshot of accumulated WebRTC statistics for monitoring and diagnostics. This can be used for adaptive bitrate decisions or debugging. ```rust use rtc::statistics::StatsSelector; use webrtc::peer_connection::PeerConnection; use std::time::Instant; async fn print_stats(pc: &dyn PeerConnection) { let now = Instant::now(); let report = pc.get_stats(now, StatsSelector::All).await; println!("Stats report: {report:#?}"); } ``` -------------------------------- ### Start Signaling with ICE Restart Disabled Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/ice-restart/index.html Calls the `doSignaling` function with `iceRestart` set to `false` to initiate the WebRTC connection without an ICE restart. ```javascript window.doSignaling(false) ``` -------------------------------- ### Run save-to-disk-vpx with Browser SDP (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-vpx/README.md Execute the save-to-disk-vpx application on Windows by redirecting the browser's Session Description Protocol (SDP) from a file. This is used to establish the WebRTC connection. ```shell ./target/debug/examples/save-to-disk-vpx < my_file ``` -------------------------------- ### Initialize and Connect DataChannel Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels-simple/demo.html Sets up the RTCPeerConnection, creates a DataChannel, and initiates the connection process by creating an offer. Handles connection and signaling state changes. ```javascript const pc = new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]}); const channel = pc.createDataChannel("chat"); // Connection state monitoring pc.onconnectionstatechange = () => log(`🔄 Connection state: ${pc.connectionState}`); pc.oniceconnectionstatechange = () => log(`🧊 ICE state: ${pc.iceConnectionState}`); pc.onsignalingstatechange = () => log(`📞 Signaling state: ${pc.signalingState}`); channel.onopen = () => { log("✅ DataChannel opened"); document.getElementById("sendBtn").disabled = false; } channel.onmessage = e => log(`📩 Server: ${e.data}`); pc.onicecandidate = event => { if(event.candidate){ fetch("/candidate", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(event.candidate), }); } }; async function start(){ try { const offer = await pc.createOffer(); await pc.setLocalDescription(offer); const res = await fetch("/offer", { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(offer), }) if (!res.ok) { throw new Error(`HTTP ${res.status}: ${res.statusText}`); } const answer = await res.json(); await pc.setRemoteDescription(answer); } catch (err) { log(`❌ Connection failed: ${err.message}`); console.error("Connection error:", err); } } function log(msg){ document.getElementById("log").textContent+=msg+"\n"; } start(); ``` -------------------------------- ### Send RTP Stream with ffmpeg Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-to-webrtc/README.md Uses ffmpeg to generate a video test stream, encode it as VP8, and send it as RTP packets to UDP port 5004 on localhost. This command is for sending video data to the rtp-to-webrtc example. ```shell ffmpeg -re -f lavfi -i testsrc=size=640x480:rate=30 -vcodec libvpx -cpu-used 5 -deadline 1 -g 10 -error-resilient 1 -auto-alt-ref 1 -f rtp "rtp://127.0.0.1:5004?pkt_size=1200" ``` -------------------------------- ### Run save-to-disk-vpx with Browser SDP (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/save-to-disk-vpx/README.md Execute the save-to-disk-vpx application on Linux or macOS, piping the browser's Session Description Protocol (SDP) from stdin. This is used to establish the WebRTC connection. ```shell echo $BROWSER_SDP | ./target/debug/examples/save-to-disk-vpx ``` -------------------------------- ### Using the Default Runtime with webrtc-rs Source: https://context7.com/webrtc-rs/webrtc/llms.txt Shows how to use the default async runtime (typically Tokio) provided by webrtc-rs. It includes spawning a background task and checking its status. ```rust // Use default (Tokio) runtime fn with_default_runtime() -> anyhow::Result<()> { block_on(async { let rt = default_runtime() .ok_or_else(|| std::io::Error::other("no async runtime found"))?; // Spawn an arbitrary background task on the WebRTC runtime let handle = rt.spawn(Box::pin(async { println!("background task running"); })); // handle.abort() to cancel; drops auto-detach println!("task finished: {}", handle.is_finished()); Ok::<_, anyhow::Error>(()) }) } ``` -------------------------------- ### Send RTP Stream with GStreamer Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-to-webrtc/README.md Uses GStreamer to generate a video test stream, encode it as VP8, and send it as RTP packets to UDP port 5004 on localhost. This pipeline is for sending video data to the rtp-to-webrtc example. ```shell gst-launch-1.0 videotestsrc ! video/x-raw,width=640,height=480,format=I420 ! vp8enc error-resilient=partitions keyframe-max-dist=10 auto-alt-ref=true cpu-used=5 deadline=1 ! rtpvp8pay ! udpsink host=127.0.0.1 port=5004 ``` -------------------------------- ### Run play-from-disk-h26x with H264 Video (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-h26x/README.md Stream H264 video and Opus audio from disk to your browser on Windows. Save the browser's Session Description to a file and use input redirection. ```shell cargo run --example play-from-disk-h26x -v rtc/examples/examples/test-data/output.264 -a rtc/examples/examples/test-data/output.ogg < my_file ``` -------------------------------- ### Run data-channels with Browser SDP (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels/README.md Run the data-channels application on Windows by redirecting the browser's Session Description Protocol (SDP) from a file. This is necessary for initiating the WebRTC connection. ```shell ./target/debug/examples/data-channels < my_file ``` -------------------------------- ### Add RTP Transceivers with Direction Control Source: https://context7.com/webrtc-rs/webrtc/llms.txt Adds RTP transceivers to a PeerConnection with explicit direction control. Use `add_transceiver_from_kind` for receive-only or send-receive scenarios, and `add_transceiver_from_track` when you have a local track to send. This example also shows how to inspect and modify transceiver direction. ```rust use rtc::rtp_transceiver::{RTCRtpTransceiverDirection, RTCRtpTransceiverInit}; use rtc::rtp_transceiver::rtp_sender::RtpCodecKind; use webrtc::peer_connection::PeerConnection; async fn setup_transceivers(pc: &dyn PeerConnection) -> webrtc::error::Result<()> { // Receive-only audio transceiver let audio_rx = pc .add_transceiver_from_kind( RtpCodecKind::Audio, Some(RTCRtpTransceiverInit { direction: RTCRtpTransceiverDirection::Recvonly, ..Default::default() }), ) .await?; println!("Audio transceiver id: {:?}", audio_rx.id()); // Send-receive video transceiver let video_sr = pc .add_transceiver_from_kind( RtpCodecKind::Video, Some(RTCRtpTransceiverInit { direction: RTCRtpTransceiverDirection::Sendrecv, ..Default::default() }), ) .await?; // Inspect current direction after negotiation println!("Video direction: {:?}", video_sr.direction().await?); println!("Video mid: {:?}", video_sr.mid().await?); // Change direction later (requires renegotiation) video_sr .set_direction(RTCRtpTransceiverDirection::Inactive) .await?; video_sr.stop().await?; Ok(()) } ``` -------------------------------- ### Create Offer and Answer for SDP Negotiation Source: https://context7.com/webrtc-rs/webrtc/llms.txt Generate an SDP offer or answer to initiate or respond to a connection. After creation, set the description as local, then exchange it with the remote peer via a signaling channel. ```rust use webrtc::peer_connection::{PeerConnection, RTCSessionDescription}; async fn offer_answer_exchange( caller: &dyn PeerConnection, callee: &dyn PeerConnection, ) -> webrtc::error::Result<()> { // ── Caller creates offer ────────────────────────────────────────────────── let offer = caller.create_offer(None).await?; caller.set_local_description(offer.clone()).await?; // ── Callee processes offer and creates answer ───────────────────────────── callee.set_remote_description(offer).await?; let answer = callee.create_answer(None).await?; callee.set_local_description(answer.clone()).await?; // ── Caller processes answer ─────────────────────────────────────────────── caller.set_remote_description(answer).await?; // Optional: read back descriptions if let Some(local) = caller.local_description().await { println!("Caller local SDP type: {:?}", local.sdp_type); } if let Some(remote) = caller.remote_description().await { println!("Caller remote SDP type: {:?}", remote.sdp_type); } Ok(()) } ``` -------------------------------- ### PeerConnection::create_offer / create_answer Source: https://context7.com/webrtc-rs/webrtc/llms.txt Generate an SDP offer (caller side) or answer (callee side) for establishing a WebRTC connection. After creation, set it as the local description and exchange it with the remote peer over your signaling channel. ```APIDOC ## `PeerConnection::create_offer` / `create_answer` — SDP negotiation Generate an SDP offer (caller side) or answer (callee side). After creation set it as the local description, then exchange it with the remote peer over your own signaling channel. ```rust use webrtc::peer_connection::{PeerConnection, RTCSessionDescription}; async fn offer_answer_exchange( caller: &dyn PeerConnection, callee: &dyn PeerConnection, ) -> webrtc::error::Result<()> { // ── Caller creates offer ────────────────────────────────────────────────── let offer = caller.create_offer(None).await?; caller.set_local_description(offer.clone()).await?; // ── Callee processes offer and creates answer ───────────────────────────── callee.set_remote_description(offer).await?; let answer = callee.create_answer(None).await?; callee.set_local_description(answer.clone()).await?; // ── Caller processes answer ─────────────────────────────────────────────── caller.set_remote_description(answer).await?; // Optional: read back descriptions if let Some(local) = caller.local_description().await { println!("Caller local SDP type: {:?}", local.sdp_type); } if let Some(remote) = caller.remote_description().await { println!("Caller remote SDP type: {:?}", remote.sdp_type); } Ok(()) } ``` ``` -------------------------------- ### Using Smol Runtime with webrtc-rs Source: https://context7.com/webrtc-rs/webrtc/llms.txt Demonstrates how to configure webrtc-rs to use the `smol` runtime instead of the default Tokio runtime. This requires enabling the `runtime-smol` feature. ```rust use webrtc::runtime::{Runtime, default_runtime, block_on}; use webrtc::peer_connection::{PeerConnectionBuilder, PeerConnectionEventHandler}; use std::sync::Arc; // Use the smol runtime instead of Tokio (requires feature = "runtime-smol") #[cfg(feature = "runtime-smol")] fn with_smol_runtime() { use webrtc::runtime::SmolRuntime; let smol_rt: Arc = Arc::new(SmolRuntime); // pass via .with_runtime(smol_rt) } ``` -------------------------------- ### Run data-channels with Browser SDP (Linux/macOS) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/data-channels/README.md Execute the data-channels application, piping the browser's Session Description Protocol (SDP) from stdin. This is used for establishing the WebRTC connection. ```shell echo $BROWSER_SDP | ./target/debug/examples/data-channels ``` -------------------------------- ### Run play-from-disk-h26x with H265 Video (Windows) Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/play-from-disk-h26x/README.md Stream H265 video and Opus audio from disk to your browser on Windows. Use the --hevc flag and input redirection with a file containing the browser's Session Description. ```shell cargo run --example play-from-disk-h26x -v rtc/examples/examples/test-data/output.265 -a rtc/examples/examples/test-data/output.ogg --hevc < my_file ``` -------------------------------- ### Create Data Channels in Rust Source: https://context7.com/webrtc-rs/webrtc/llms.txt Demonstrates creating both reliable ordered and unreliable unordered data channels. Configure channel properties using `RTCDataChannelInit`. Event handling for messages and channel state changes must run in a spawned task. ```rust use webrtc::data_channel::{DataChannel, DataChannelEvent, RTCDataChannelInit}; use webrtc::peer_connection::PeerConnection; use std::sync::Arc; use bytes::BytesMut; async fn create_and_use_channel( pc: &dyn PeerConnection, runtime: Arc, ) -> webrtc::error::Result<()> { // Reliable ordered channel (default) let dc_reliable = pc.create_data_channel("chat", None).await?; // Unreliable unordered channel (max throughput, no retransmits) let dc_unreliable = pc .create_data_channel( "metrics", Some(RTCDataChannelInit { ordered: false, max_retransmits: Some(0), ..Default::default() }), ) .await?; println!("Channel '{}' id={}", dc_reliable.label().await?, dc_reliable.id()); // Event loop — must run in a spawned task runtime.spawn(Box::pin(async move { while let Some(evt) = dc_reliable.poll().await { match evt { DataChannelEvent::OnOpen => { dc_reliable.send_text("hello").await.ok(); dc_reliable .send(BytesMut::from(&b"binary payload"[..])) .await .ok(); } DataChannelEvent::OnMessage(msg) => { println!("Got {} bytes", msg.data.len()); } DataChannelEvent::OnClose => break, _ => {} } } })); Ok(()) } ``` -------------------------------- ### Create and Configure PeerConnection with PeerConnectionBuilder Source: https://context7.com/webrtc-rs/webrtc/llms.txt Use PeerConnectionBuilder to configure ICE servers, media codecs, interceptors, runtime, and event handlers before building the PeerConnection. Ensure an async runtime is available. ```rust use std::sync::Arc; use webrtc::peer_connection::{ MediaEngine, PeerConnection, PeerConnectionBuilder, PeerConnectionEventHandler, RTCConfigurationBuilder, RTCIceServer, Registry, register_default_interceptors, }; use webrtc::runtime::{block_on, default_runtime}; #[derive(Clone)] struct MyHandler; #[async_trait::async_trait] impl PeerConnectionEventHandler for MyHandler {} fn main() -> anyhow::Result<()> { block_on(async { let mut media_engine = MediaEngine::default(); media_engine.register_default_codecs()?; let registry = register_default_interceptors(Registry::new(), &mut media_engine)?; let config = RTCConfigurationBuilder::new() .with_ice_servers(vec![RTCIceServer { urls: vec!["stun:stun.l.google.com:19302".to_string()], ..Default::default() }]) .build(); let runtime = default_runtime() .ok_or_else(|| std::io::Error::other("no async runtime found"))?; let pc = PeerConnectionBuilder::new() .with_configuration(config) .with_media_engine(media_engine) .with_interceptor_registry(registry) .with_handler(Arc::new(MyHandler)) .with_runtime(runtime) .with_udp_addrs(vec!["0.0.0.0:0".to_string()]) .build() .await?; // pc now implements PeerConnection pc.close().await?; Ok::<_, anyhow::Error>(()) }) } ``` -------------------------------- ### PeerConnectionBuilder — Create a peer connection Source: https://context7.com/webrtc-rs/webrtc/llms.txt Demonstrates how to use PeerConnectionBuilder to configure and create a new RTCPeerConnection. This includes setting up ICE servers, media codecs, interceptors, and the event handler. ```APIDOC ## PeerConnectionBuilder — Create a peer connection ### Description Builder for `PeerConnectionImpl`. Configures ICE servers, media codecs, interceptors, runtime, and the event handler before constructing and spawning the internal I/O driver. Returns `impl PeerConnection` (object-safe trait). ### Usage Example ```rust use std::sync::Arc; use webrtc::peer_connection::{ MediaEngine, PeerConnection, PeerConnectionBuilder, PeerConnectionEventHandler, RTCConfigurationBuilder, RTCIceServer, Registry, register_default_interceptors, }; use webrtc::runtime::{block_on, default_runtime}; #[derive(Clone)] struct MyHandler; #[async_trait::async_trait] impl PeerConnectionEventHandler for MyHandler {} fn main() -> anyhow::Result<()> { block_on(async { let mut media_engine = MediaEngine::default(); media_engine.register_default_codecs()?; let registry = register_default_interceptors(Registry::new(), &mut media_engine)?; let config = RTCConfigurationBuilder::new() .with_ice_servers(vec![RTCIceServer { urls: vec!["stun:stun.l.google.com:19302".to_string()], ..Default::default() }]) .build(); let runtime = default_runtime() .ok_or_else(|| std::io::Error::other("no async runtime found"))?; let pc = PeerConnectionBuilder::new() .with_configuration(config) .with_media_engine(media_engine) .with_interceptor_registry(registry) .with_handler(Arc::new(MyHandler)) .with_runtime(runtime) .with_udp_addrs(vec!["0.0.0.0:0".to_string()]) .build() .await?; // pc now implements PeerConnection pc.close().await?; Ok::<_, anyhow::Error>(()) }) } ``` ``` -------------------------------- ### Run rtp-forwarder on Windows Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-forwarder/README.md Execute the rtp-forwarder on Windows by redirecting a file containing the browser's SessionDescription to its standard input. ```shell ./target/debug/examples/rtp-forwarder < my_file ``` -------------------------------- ### Run rtp-forwarder on Linux/macOS Source: https://github.com/webrtc-rs/webrtc/blob/master/examples/rtp-forwarder/README.md Execute the rtp-forwarder on Linux or macOS by piping the browser's SessionDescription to its standard input. ```shell echo $BROWSER_SDP | ./target/debug/examples/rtp-forwarder ```