### Run the http-post example Source: https://github.com/algesten/str0m/blob/main/README.md Starts the http-post example, which receives media data from a browser client. It is single-threaded and simpler than the chat example, serving as a good starting point to understand the API. ```bash cargo run --example http-post ``` -------------------------------- ### Run the chat example Source: https://github.com/algesten/str0m/blob/main/README.md Starts the chat example, which connects multiple browsers and acts as an SFU. The log prompts to connect a browser to https://10.0.0.103:3000, which may cause a security warning. ```bash cargo run --example chat ``` -------------------------------- ### WebRTC Post example: startCam and startMic functions Source: https://github.com/algesten/str0m/blob/main/examples/http-post.html Functions to enable camera and microphone streams using getUserMedia. They disable the corresponding button and the RTC button while acquiring the stream, then re-enable the RTC button. ```javascript async function startCam() { byId('cam').disabled = true; byId('rtc').disabled = true; streamCam = await navigator.mediaDevices.getUserMedia({ video: true, }); byId('rtc').disabled = false; } ``` ```javascript async function startMic() { byId('mic').disabled = true; byId('rtc').disabled = true; streamMic = await navigator.mediaDevices.getUserMedia({ audio: true, }); byId('rtc').disabled = false; } ``` -------------------------------- ### WebRTC Post example: startRtc function Source: https://github.com/algesten/str0m/blob/main/examples/http-post.html Creates an RTCPeerConnection, optionally creates a data channel, adds camera/mic tracks, creates an offer, sends it via POST to the same URL, and sets the remote description from the answer. ```javascript async function startRtc() { byTag('button').forEach(b => b.disabled = true); if (startChannel) { dataChannel = rtc.createDataChannel("myChannel"); dataChannel.onopen = () => { console.log("datachannel open"); }; dataChannel.onclose = () => { console.log("datachannel close"); }; let counter = 0; setInterval(() => { if (dataChannel.readyState != 'open') { return; } dataChannel.send(`Counter ${counter}`); counter++; }, 1000); } if (streamCam) { rtc.addTrack(streamCam.getTracks()[0], streamCam); } if (streamMic) { rtc.addTrack(streamMic.getTracks()[0], streamMic); } const offer = await rtc.createOffer(); rtc.setLocalDescription(offer); console.log(offer.sdp.split('\r\n')); const res = await fetch('', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(offer), }); const answer = await res.json(); rtc.setRemoteDescription(answer); console.log(answer.sdp.split('\r\n')); } ``` -------------------------------- ### WebRTC Post example: startDataChannel function Source: https://github.com/algesten/str0m/blob/main/examples/http-post.html Enables the data channel by setting startChannel to true and disabling the data button. ```javascript async function startDataChannel() { byId('data').disabled = true; startChannel = true; } ``` -------------------------------- ### Active connection setup Source: https://github.com/algesten/str0m/blob/main/README.md Steps to open an active connection where we make the initial OFFER and wait for a remote ANSWER. Requires adding a local ICE candidate, creating a media line, and applying the answer. ```rust // Instantiate a new Rtc instance. let mut rtc = Rtc::new(Instant::now()); // Add some ICE candidate such as a locally bound UDP port. let addr = "1.2.3.4:5000".parse().unwrap(); let candidate = Candidate::host(addr, "udp").unwrap(); rtc.add_local_candidate(candidate); // Create a `SdpApi`. The change lets us make multiple changes // before sending the offer. let mut change = rtc.sdp_api(); // Do some change. A valid OFFER needs at least one "m-line" (media). let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); // Get the offer. let (offer, pending) = change.apply().unwrap(); // Forward the offer to the remote peer and await the answer. // How to transfer this is outside the scope for this library. let answer = todo!(); // Apply answer. rtc.sdp_api().accept_answer(pending, answer).unwrap(); // Go to _run loop_ ``` -------------------------------- ### Quick start: Create IceAgent and add local candidate Source: https://github.com/algesten/str0m/blob/main/crates/is/README.md Initializes an IceAgent with random credentials, adds a local UDP candidate, and notes that credentials and candidates must be exchanged with the remote peer via a signalling channel before running the loop until IceConnectionState::Connected. ```rust use is::{IceAgent, IceCreds, Candidate}; // Create an agent with random credentials. let mut agent = IceAgent::new(IceCreds::new()); // Tell the agent about a local socket. let addr = "192.168.1.100:5000".parse().unwrap(); agent.add_local_candidate(Candidate::host(addr, "udp").unwrap()); // Exchange credentials and candidates with the remote peer via your // signalling channel, then run the loop above until // IceConnectionState::Connected. ``` -------------------------------- ### Passive connection setup Source: https://github.com/algesten/str0m/blob/main/README.md Steps to open a passive connection where the remote peer makes the initial OFFER. Requires adding a local ICE candidate and accepting the offer via the SDP API. ```rust // Instantiate a new Rtc instance. let mut rtc = Rtc::new(Instant::now()); // Add some ICE candidate such as a locally bound UDP port. let addr = "1.2.3.4:5000".parse().unwrap(); let candidate = Candidate::host(addr, "udp").unwrap(); rtc.add_local_candidate(candidate); // Accept an incoming offer from the remote peer // and get the corresponding answer. let offer = todo!(); let answer = rtc.sdp_api().accept_offer(offer).unwrap(); // Forward the answer to the remote peer. // Go to _run loop_ ``` -------------------------------- ### WebRTC Chat Client JavaScript Source: https://github.com/algesten/str0m/blob/main/examples/chat.html Client-side logic for a WebRTC chat example. Handles camera/mic capture, data channel signaling, and ICE connection state changes. Includes commented-out simulcast configuration and a hardcoded simulcast level in chat.rs. ```javascript let streamCam; let streamMic; let dataChannel; let rtc = new RTCPeerConnection(); rtc.oniceconnectionstatechange = () => { byId('ice_status').innerText = rtc.iceConnectionState; if (rtc.iceConnectionState == 'disconnected' || rtc.iceConnectionState == 'failed') { if (streamCam) { streamCam.getTracks()[0]?.stop(); } if (streamMic) { streamMic.getTracks()[0]?.stop(); } rtc.close(); byId('rtc').disabled = true; byId('cam').disabled = true; byId('mic').disabled = true; } }; const byId = (id) => document.getElementById(id); const byTag = (tag) => [].slice.call(document.getElementsByTagName(tag)); var callback = null; async function negotiate() { const offer = await rtc.createOffer(); console.log('do offer', offer.sdp.split('\r\n')); rtc.setLocalDescription(offer); await dataChannel.send(JSON.stringify(offer)); const json = await new Promise((rs) => { callback = rs; }); const answer = JSON.parse(json); console.log('received answer', answer.sdp.split('\r\n')); rtc.setRemoteDescription(answer); } async function handleOffer(json) { const offer = JSON.parse(json); console.log('handle offer', offer.sdp.split('\r\n')); rtc.setRemoteDescription(offer); const answer = await rtc.createAnswer(); console.log('offer response', answer.sdp.split('\r\n')); rtc.setLocalDescription(answer); await dataChannel.send(JSON.stringify(answer)); } async function startCam() { byId('cam').disabled = true; streamCam = await navigator.mediaDevices.getUserMedia({ video: { width: 640, height: 360, }, }); const tr = rtc.addTransceiver(streamCam.getTracks()[0], { direction: "sendonly", streams: [streamCam], // This table shows the valid values for simulcast. // // https://webrtc.googlesource.com/src/+/branch-heads/49/talk/media/webrtc/simulcast.cc // These tables describe from which resolution we can use how many // simulcast layers at what bitrates (maximum, target, and minimum). // Important!! Keep this table from high resolution to low resolution. // const SimulcastFormat kSimulcastFormats[] = { // {1920, 1080, 3, 5000, 4000, 800}, // {1280, 720, 3, 2500, 2500, 600}, // {960, 540, 3, 900, 900, 450}, // {640, 360, 2, 700, 500, 150}, // {480, 270, 2, 450, 350, 150}, // {320, 180, 1, 200, 150, 30}, // {0, 0, 1, 200, 150, 30} // }; // Uncomment this to enable simulcast. The actual selected // simulcast level is hardcoded in chat.rs. // sendEncodings: [ // { rid: "h", maxBitrate: 700 * 1024 }, // { rid: "l", maxBitrate: 150 * 1024 } // ] }); await negotiate(); } async function startMic() { byId('mic').disabled = true; streamMic = await navigator.mediaDevices.getUserMedia({ audio: true, }); const tr = rtc.addTransceiver(streamMic.getTracks()[0], { streams: [streamMic], direction: "sendonly" }); await negotiate(); } rtc.ontrack = (e) => { console.log('ontrack', e.track); const track = e.track; const domId = `media-${track.id}`; const el = document.createElement('video'); if (byId(domId)) { // we aleady have this track return; } el.id = domId; el.width = 500; byId('media').appendChild(el); el.controls = true; el.autoplay = true; setTimeout(() => { const media = new MediaStream(); media.addTrack(track); el.srcObject = media; }, 1); track.addEventListener('mute', () => { console.log('track muted', track); el.parentNode.removeChild(el); }); track.addEventListener('unmute', () => { console.log('track unmuted', track); byId('media').appendChild(el); }); }; async function startRtc() { byId('rtc').disabled = true; dataChannel = rtc.createDataChannel("offer/answer"); dataChannel.onmessage = (event) => { let json = JSON.parse(event.data); if (json.type == 'offer') { // no callback probably means it's an offer handleOffer(event.data); } else if (json.type == 'answer') { callback(event.data); callback = null; } }; dataChannel.onopen = () => { byId('chan_status').innerText = ''; byId('mic').disabled = false; byId('cam').disabled = false; }; const offer = await rtc.createOffer(); rtc.setLocalDescription(offer); console.log('POST offer', offer.sdp.split('\r\n')); const res = await fetch('/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(offer), }); const answer = await res.json(); rtc.setRemoteDescription(answer); console.log('POST answer', answer.sdp.split('\r\n')); } ``` -------------------------------- ### Install process-wide default crypto provider (str0m_rust_crypto) Source: https://github.com/algesten/str0m/blob/main/README.md Sets the RustCrypto backend as the process-wide default at startup. Calling this twice will panic. The 'rust-crypto' feature flag does not need to be enabled to use the crate directly. ```rust // Set process default (will panic if called twice) // No need to enable the "rust-crypto" feature flag str0m_rust_crypto::default_provider().install_process_default(); ``` -------------------------------- ### Direct usage of str0m_wincrypto crate Source: https://github.com/algesten/str0m/blob/main/crypto/wincrypto/README.md For advanced use cases, use the crate directly without the feature flag. Install the provider as process-wide default or configure it per Rtc instance. ```rust use str0m::Rtc; use std::sync::Arc; // Set as process-wide default str0m_wincrypto::default_provider().install_process_default(); // Or configure per-instance let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_wincrypto::default_provider())) .build(); ``` -------------------------------- ### Direct usage of str0m-openssl crate Source: https://github.com/algesten/str0m/blob/main/crypto/openssl/README.md For advanced use cases, use the crate directly without the feature flag. Install the default provider process-wide or configure it per-instance via `Rtc::builder()`. ```rust use str0m::Rtc; use std::sync::Arc; // Set as process-wide default str0m_openssl::default_provider().install_process_default(); // Or configure per-instance let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_openssl::default_provider())) .build(); ``` -------------------------------- ### Direct usage of str0m-aws-lc-rs crate Source: https://github.com/algesten/str0m/blob/main/crypto/aws-lc-rs/README.md Shows advanced direct usage: installs the provider as process-wide default or sets it per Rtc instance. ```rust use str0m::Rtc; use std::sync::Arc; // Set as process-wide default str0m_aws_lc_rs::default_provider().install_process_default(); // Or configure per-instance let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_aws_lc_rs::default_provider())) .build(); ``` -------------------------------- ### Direct usage of str0m-rust-crypto Source: https://github.com/algesten/str0m/blob/main/crypto/rust-crypto/README.md For advanced use cases, install the provider process-wide or configure it per Rtc instance. ```rust use str0m::Rtc; use std::sync::Arc; // Set as process-wide default str0m_rust_crypto::default_provider().install_process_default(); // Or configure per-instance let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_rust_crypto::default_provider())) .build(); ``` -------------------------------- ### Publish crates bottom-up Source: https://github.com/algesten/str0m/blob/main/docs/RELEASE.md Commands to publish all workspace crates in dependency order, waiting for each to land on the index. Use --no-verify for str0m-wincrypto because the windows crate fails to build on macOS. ```bash cargo publish -p str0m-proto cargo publish -p is cargo publish -p str0m-aws-lc-rs cargo publish -p str0m-rust-crypto cargo publish -p str0m-openssl cargo publish -p str0m-apple-crypto cargo publish -p str0m-wincrypto --no-verify cargo publish -p str0m ``` -------------------------------- ### Check latest versions on crates.io Source: https://github.com/algesten/str0m/blob/main/docs/RELEASE.md Shell loop that queries crates.io API for each crate and prints its max_version. Useful for verifying the state of published crates. ```bash for c in str0m str0m-proto is str0m-aws-lc-rs str0m-rust-crypto \ str0m-openssl str0m-apple-crypto str0m-wincrypto; do echo -n "$c: " curl -s "https://crates.io/api/v1/crates/$c" \ | python3 -c "import sys,json; print(json.load(sys.stdin)['crate']['max_version'])" done ``` -------------------------------- ### Direct usage of str0m_apple_crypto crate Source: https://github.com/algesten/str0m/blob/main/crypto/apple-crypto/README.md Shows how to use the crate directly without the feature flag, either as a process-wide default or per-instance via Rtc::builder(). ```rust use str0m::Rtc; use std::sync::Arc; // Set as process-wide default str0m_apple_crypto::default_provider().install_process_default(); // Or configure per-instance let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_apple_crypto::default_provider())) .build(); ``` -------------------------------- ### Tag and push release Source: https://github.com/algesten/str0m/blob/main/docs/RELEASE.md Commands to tag the release with the version (e.g., 0.19.0) and push both the commit and the tag to the remote. ```bash git tag 0.19.0 git push && git push --tags ``` -------------------------------- ### Send media data with Writer::write in str0m Source: https://github.com/algesten/str0m/blob/main/README.md Shows how to obtain a media writer for a Mid, select a payload type from the writer's payload parameters, and write RTP data with wallclock and media time. Writer::write is a mutation, so after writing you must drain Rtc::poll_output to Output::Timeout before the next mutation on the Rtc. ```rust // Obtain mid from Event::MediaAdded let mid: Mid = todo!(); // Create a media writer for the mid. let writer = rtc.writer(mid).unwrap(); // Get the payload type (pt) for the wanted codec. let pt = writer.payload_params().nth(0).unwrap().pt(); // Write the data let wallclock = todo!(); // Absolute time of the data let media_time = todo!(); // Media time, in RTP time let data: &[u8] = todo!(); // Actual data writer.write(pt, wallclock, media_time, data).unwrap(); ``` -------------------------------- ### Enable openssl-dimpl feature for DTLS 1.3 Source: https://github.com/algesten/str0m/blob/main/crypto/openssl/README.md Use the `openssl-dimpl` feature to enable DTLS 1.3 support via Dimpl. This is kept separate from the standard `openssl` feature and may become the only implementation in the future. ```toml [dependencies] str0m = { version = "0.14", default-features = false, features = ["openssl-dimpl"] } ``` -------------------------------- ### Cargo.toml dependency with apple-crypto feature Source: https://github.com/algesten/str0m/blob/main/crypto/apple-crypto/README.md Adds the str0m dependency with the apple-crypto feature flag to enable the Apple CryptoKit/CommonCrypto/Security backend. ```toml [dependencies] str0m = { version = "0.14", features = ["apple-crypto"] } ``` -------------------------------- ### Crate dependency graph Source: https://github.com/algesten/str0m/blob/main/docs/RELEASE.md ASCII diagram showing the dependency graph of str0m and its workspace crates. str0m depends on is, aws-lc-rs, rust-crypto, openssl, apple-crypto, and wincrypto, all of which depend on str0m-proto. str0m-netem is dev-only and not pulled by published str0m. ```text str0m | +------+-----------+-----+-----+------------+----------+ | | | | | | v v v v v v is aws-lc-rs rust-crypto openssl apple-crypto wincrypto | | | | | | +------+-----------+-----+-----+------------+----------+ | v str0m-proto ``` -------------------------------- ### Set crypto provider per Rtc instance (str0m_rust_crypto) Source: https://github.com/algesten/str0m/blob/main/README.md Configures a custom crypto provider for a single Rtc instance using the RustCrypto backend. The provider is passed as an Arc to the builder before building with the current Instant. ```rust use std::sync::Arc; use std::time::Instant; use str0m::Rtc; let rtc = Rtc::builder() .set_crypto_provider(Arc::new(str0m_rust_crypto::default_provider())) .build(Instant::now()); ``` -------------------------------- ### Enable wincrypto feature flag in Cargo.toml Source: https://github.com/algesten/str0m/blob/main/crypto/wincrypto/README.md Adds the wincrypto feature to the str0m dependency with default features disabled. This is the primary way to use the Windows CNG crypto backend. ```toml [dependencies] str0m = { version = "0.23", default-features = false, features = ["wincrypto"] } ``` -------------------------------- ### Type mismatch error when proto versions don't unify Source: https://github.com/algesten/str0m/blob/main/docs/RELEASE.md Error message shown when a leaf crate is published against an old proto version, causing two proto versions in the dep tree. Types like TcpType won't unify and verification fails. ```text expected `str0m_proto::net::TcpType`, found `TcpType` ``` -------------------------------- ### Canonical run loop for driving an Rtc instance Source: https://github.com/algesten/str0m/blob/main/README.md Implements the six-step run loop for a str0m Rtc instance: wait for timeout/input, perform one mutation, drain poll_output until Output::Timeout, then repeat. Uses a blocking UDP socket with a read timeout; for async, select! over futures. The loop enforces the single-mutation invariant: every mutation must be followed by a complete drain to Timeout before the next mutation. ```rust // A UdpSocket we obtained _somehow_. let socket: UdpSocket = todo!(); // Buffer for reading incoming UDP packets. let mut buf = vec![0; 2000]; loop { // === Steps 3-5: drain poll_output until we get the next timeout. === let timeout = loop { match rtc.poll_output().unwrap() { // Step 5: a Timeout exits the drain loop. Output::Timeout(t) => break t, // Step 4: transmit on the socket and keep draining. // The destination IP comes from the ICE agent and may // change during the session. Output::Transmit(t) => { socket.send_to(&t.contents, t.destination).unwrap(); } // Step 4: hand the event to the application and keep draining. // Events are mainly incoming media data from the remote peer, // but also data channel data and statistics. Output::Event(e) => { if e == Event::IceConnectionStateChange(IceConnectionState::Disconnected) { return; } // TODO: handle other events here, such as incoming media data. } } }; // === Step 1: wait for ONE of: the timeout firing, an incoming // packet, or application-side data. The example below uses a // blocking UDP socket with a read timeout. With async you would // `select!` over multiple futures; with application-side data you // would also include a channel. // // set_read_timeout(Some(ZERO)) is not allowed, so clamp to >= 1ms. let duration = (timeout - Instant::now()).max(Duration::from_millis(1)); socket.set_read_timeout(Some(duration)).unwrap(); buf.resize(2000, 0); // === Step 2: take ONE event and feed it as Input === let input = match socket.recv_from(&mut buf) { Ok((n, source)) => { buf.truncate(n); Input::Receive( Instant::now(), Receive { proto: Protocol::Udp, source, destination: socket.local_addr().unwrap(), contents: buf.as_slice().try_into().unwrap(), }, ) } // The socket read timed out — feed Input::Timeout to advance // the engine to the deadline. WouldBlock is the unix error, // TimedOut is the windows error. Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => { Input::Timeout(Instant::now()) } Err(e) => { eprintln!("Error: {:?}", e); return; } }; rtc.handle_input(input).unwrap(); // === Step 6: back to the top of the outer loop (goto step 3). === } ``` -------------------------------- ### Enable rust-crypto feature in Cargo.toml Source: https://github.com/algesten/str0m/blob/main/crypto/rust-crypto/README.md Adds the rust-crypto backend to str0m via the feature flag, disabling default features. ```toml [dependencies] str0m = { version = "0.14", default-features = false, features = ["rust-crypto"] } ``` -------------------------------- ### Enable openssl feature in Cargo.toml Source: https://github.com/algesten/str0m/blob/main/crypto/openssl/README.md Add the `openssl` feature to the `str0m` dependency to use the OpenSSL backend. Disables default features and specifies version 0.14. ```toml [dependencies] str0m = { version = "0.14", default-features = false, features = ["openssl"] } ``` -------------------------------- ### Enable RTP mode with set_rtp_mode(true) Source: https://github.com/algesten/str0m/blob/main/README.md Use this snippet to enable RTP mode for an Rtc instance. This disables MediaEvent and the Writer::write API, and provides Event::RtpPacket, StreamTx::write_rtp, and StreamRx::request_keyframe. ```rust let rtc = Rtc::builder() // Enable RTP mode for this Rtc instance. // This disables `MediaEvent` and the `Writer::write` API. .set_rtp_mode(true) .build(Instant::now()); ``` -------------------------------- ### Add str0m with aws-lc-rs feature flag in Cargo.toml Source: https://github.com/algesten/str0m/blob/main/crypto/aws-lc-rs/README.md Declares str0m as a dependency with the default aws-lc-rs crypto backend enabled via the feature flag. ```toml [dependencies] str0m = "0.14" ```