From 5019bed3240d51c042bfe4ea3ec5980d06bd0ee1 Mon Sep 17 00:00:00 2001 From: selikhov Date: Sat, 3 Oct 2026 22:13:31 +0300 Subject: [PATCH] Answer a streamer's new offer on the running connection Watching a stream from the official client failed. Its log shows why: after our answer it decided our codec choice did not suit it ("remote peer is using unsupported codec, realign") and sent a new offer on the same connection, a renegotiation. Voelin answered every offer with a new peer: new ICE credentials, new DTLS fingerprint (the official client logged both answers, they differ), so the connection the official client kept using was gone and no picture came. - `Peer::renegotiate` answers a new offer on the running peer (str0m `accept_offer` on the same Rtc): same ICE credentials and fingerprint. - The viewer uses it for an `offer` signal while it has a connection; a `reconnectOffer` still starts a new one. - str0m answers a renegotiation in the codec order the connection was built with, so a streamer re-offering another codec first kept sending the old one; `order_like_offer` puts the answer's payload types in the new offer's order. Tests: a unit test (a str0m offerer adds audio in a new offer; same ICE credentials and fingerprint, audio answered) and the order helper; the browser interop test `browser_renegotiates_with_rust` (Chromium streams VP8, re-offers VP9 on the same connection, VP9 frames arrive), passing with Chromium 152. Co-Authored-By: Claude Opus 5.5 --- crates/voelin-stream/src/peer.rs | 99 +++++++++++++++++++ crates/voelin-stream/src/session.rs | 12 +++ crates/voelin-stream/tests/browser_interop.rs | 31 ++++++ docs/protocol-notes/ts6-streaming.md | 16 +++ tests/interop/README.md | 1 + tests/interop/browser-peer.cjs | 15 +++ 6 files changed, 174 insertions(+) diff --git a/crates/voelin-stream/src/peer.rs b/crates/voelin-stream/src/peer.rs index 3d91125..ff5fdc7 100644 --- a/crates/voelin-stream/src/peer.rs +++ b/crates/voelin-stream/src/peer.rs @@ -252,6 +252,7 @@ pub struct MediaFrame { enum Cmd { Answer(String, oneshot::Sender>), + Offer(String, oneshot::Sender>), RemoteCandidate(String), Write { kind: MediaKind, time: MediaTime, data: Arc<[u8]>, rid: Option }, RequestKeyframe, @@ -372,6 +373,16 @@ impl Peer { rx.await.map_err(|_| PeerError::Closed)? } + /// Viewer side: answer a new offer of the streamer on this connection + /// (a renegotiation: the same ICE credentials and DTLS fingerprint). + /// The official client re-offers when the codec our answer chose is one + /// it does not encode, and expects the answer from the same peer. + pub async fn renegotiate(&self, offer: &str) -> Result { + let (tx, rx) = oneshot::channel(); + self.cmd.send(Cmd::Offer(offer.to_owned(), tx)).map_err(|_| PeerError::Closed)?; + rx.await.map_err(|_| PeerError::Closed)? + } + /// Add a trickled remote candidate (`candidate:...`, `a=` prefix optional). pub fn add_remote_candidate(&self, candidate: &str) { let _ = self.cmd.send(Cmd::RemoteCandidate(candidate.to_owned())); @@ -496,6 +507,40 @@ fn build_rtc( dtls::build_rtc(rtc_config, &config.srtp_profiles) } +/// `answer` with the payload types of each media line in the order of the +/// same media line of `offer` (those the offer lacks last). The offerer sends +/// the answer's first codec; str0m answers a new offer on a running +/// connection in the codec order the connection was built with, so without +/// this a streamer that re-offers with another codec first keeps sending the +/// old one. Only the `m=` line order changes, which str0m's own state does +/// not depend on. +fn order_like_offer(answer: &str, offer: &str) -> String { + let offered: Vec> = offer + .lines() + .filter_map(|l| l.trim_end().strip_prefix("m=")) + .map(|m| m.split_whitespace().skip(3).collect()) + .collect(); + let mut section = 0; + let mut out = String::with_capacity(answer.len()); + for line in answer.split_inclusive('\n') { + let Some(media) = line.trim_end().strip_prefix("m=") else { + out.push_str(line); + continue; + }; + let mut parts: Vec<&str> = media.split_whitespace().collect(); + if let Some(order) = offered.get(section) + && parts.len() > 3 + { + parts[3..].sort_by_key(|pt| order.iter().position(|o| o == pt).unwrap_or(usize::MAX)); + } + section += 1; + out.push_str("m="); + out.push_str(&parts.join(" ")); + out.push_str(&line[line.trim_end().len()..]); + } + out +} + /// The video codecs of the first video media line of `sdp`, in offered order. fn offered_video_codecs(sdp: &str) -> Vec { let mut pts: Vec<&str> = Vec::new(); @@ -826,6 +871,13 @@ impl Task { let result = self.accept_answer(&sdp); let _ = reply.send(result); } + Cmd::Offer(sdp, reply) => { + let result = SdpOffer::from_sdp_string(&sdp) + .map_err(|e| PeerError::Sdp(e.to_string())) + .and_then(|offer| Ok(self.rtc.sdp_api().accept_offer(offer)?.to_sdp_string())) + .map(|answer| order_like_offer(&answer, &sdp)); + let _ = reply.send(result); + } Cmd::RemoteCandidate(line) => { let line = line.trim().trim_start_matches("a="); match Candidate::from_sdp_string(line) { @@ -951,6 +1003,53 @@ mod tests { assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}"); } + /// The ICE username fragment and DTLS fingerprint of an SDP. + fn transport(sdp: &str) -> (String, String) { + let line = |prefix: &str| { + sdp.lines().find_map(|l| l.strip_prefix(prefix)).unwrap_or_default().trim().to_owned() + }; + (line("a=ice-ufrag:"), line("a=fingerprint:")) + } + + /// A streamer's new offer (the official client re-offers when it does not + /// encode the codec our answer chose) is answered on the same connection: + /// same ICE credentials and DTLS fingerprint, the new media answered. + #[tokio::test] + async fn a_new_offer_is_answered_on_the_same_connection() { + let mut streamer = RtcConfig::new() + .clear_codecs() + .enable_vp8(true) + .enable_opus(true) + .build(Instant::now()); + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Video, Direction::SendOnly, None, None, None); + let (offer, pending) = api.apply().unwrap(); + let (peer, answer) = + Peer::answer(&PeerConfig::loopback(), &offer.to_sdp_string()).await.unwrap(); + let answer_sdp = SdpAnswer::from_sdp_string(&answer).unwrap(); + streamer.sdp_api().accept_answer(pending, answer_sdp).unwrap(); + + let mut api = streamer.sdp_api(); + api.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _pending) = api.apply().unwrap(); + let again = peer.renegotiate(&offer.to_sdp_string()).await.unwrap(); + assert_eq!(transport(&again), transport(&answer), "{again}"); + assert!(again.lines().all(|l| !l.is_empty() || l.ends_with('\r')), "line ends kept"); + assert!(!transport(&again).0.is_empty()); + assert!(again.contains("m=audio") && again.contains("opus/48000"), "{again}"); + } + + #[test] + fn answers_follow_the_offers_codec_order() { + let offer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45\r\n"; + let answer = "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96 97 7 98 99\r\na=rtpmap:96 VP8/90000\r\n"; + assert_eq!( + order_like_offer(answer, offer), + "v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\nm=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 7\r\na=rtpmap:96 VP8/90000\r\n" + ); + assert_eq!(order_like_offer("v=0\r\n", offer), "v=0\r\n"); + } + /// An offer of codecs we cannot decode is refused with the reason, not /// answered with a video section the streamer cannot parse. #[tokio::test] diff --git a/crates/voelin-stream/src/session.rs b/crates/voelin-stream/src/session.rs index 5a58e47..eabba6d 100644 --- a/crates/voelin-stream/src/session.rs +++ b/crates/voelin-stream/src/session.rs @@ -1307,6 +1307,18 @@ impl ViewerSession { } } StreamNotification::Signaling { json, .. } => match Signal::parse(json) { + // A new offer on the running connection (the official client + // re-offers when it does not encode the codec we chose) is + // answered by the same peer; `reconnectOffer` starts a new one. + Ok(Signal::Offer { sdp, reconnect: false }) if self.peer.is_some() => { + let peer = self.peer.as_ref().expect("checked above"); + match peer.renegotiate(&sdp).await { + Ok(sdp) => self.signal(Signal::Answer { sdp }, out), + Err(e) => { + self.fail(format!("cannot answer the streamer's new offer: {e}"), out) + } + } + } Ok(Signal::Offer { sdp, .. }) => self.answer(&sdp, out).await, Ok(Signal::IceCandidate { candidate, .. }) => { if let Some(peer) = &self.peer { diff --git a/crates/voelin-stream/tests/browser_interop.rs b/crates/voelin-stream/tests/browser_interop.rs index 538c55c..eea7bea 100644 --- a/crates/voelin-stream/tests/browser_interop.rs +++ b/crates/voelin-stream/tests/browser_interop.rs @@ -273,3 +273,34 @@ async fn browser_streams_to_rust() { assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}"); browser.quit().await; } + +/// Chromium streams VP8, then renegotiates to VP9 on the same connection, as +/// the official client re-offers when it does not encode the codec our +/// answer chose: our viewer answers on the same peer and keeps receiving, +/// now VP9. +#[tokio::test(flavor = "multi_thread")] +async fn browser_renegotiates_with_rust() { + if !enabled() { + eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)"); + return; + } + let _ = tracing_subscriber::fmt().with_env_filter("warn").with_test_writer().try_init(); + let mut browser = Browser::start().await; + let offer = browser.call(json!({ "op": "offer", "codec": "VP8", "trickle": false })).await; + let (mut peer, answer) = + Peer::answer(&PeerConfig::loopback(), offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": answer })).await; + wait_connected(&mut peer).await; + let before = receive(&mut peer, Duration::from_secs(5), 30).await; + assert!(before.video.get(Codec::Vp8) >= 30, "before: {:?}", before.video); + + let offer = browser.call(json!({ "op": "reoffer", "codec": "VP9" })).await; + let again = peer.renegotiate(offer["sdp"].as_str().unwrap()).await.unwrap(); + browser.call(json!({ "op": "accept", "sdp": again })).await; + let after = receive(&mut peer, Duration::from_secs(8), 30).await; + eprintln!("after the new offer: video {:?}, audio {:?}", after.video, after.audio); + assert!(after.video.get(Codec::Vp9) >= 30, "after: {:?}", after.video); + let stats = browser.call(json!({ "op": "stats" })).await; + assert_eq!(stats["connectionState"], "connected", "{stats:#}"); + browser.quit().await; +} diff --git a/docs/protocol-notes/ts6-streaming.md b/docs/protocol-notes/ts6-streaming.md index 5213328..d6b9aa9 100644 --- a/docs/protocol-notes/ts6-streaming.md +++ b/docs/protocol-notes/ts6-streaming.md @@ -262,6 +262,22 @@ the official client itself is still to be confirmed: the beta needs a myTeamSpeak sign-in on first start, so it cannot run from a throwaway profile. +### The official client re-offers (confirmed, client 6.0.0-beta4.1, 2026-10-03) + +Streaming from the official client to Voelin, its log shows: our answer +(H.264, VP9, VP8 — no AV1, which the app did not decode) → "remote peer is +using unsupported codec, realign" → a new `offer` signal on the same +connection → our answer → `ENCODER create: H264`. The new offer is a +renegotiation of the running connection: the answer must come from the same +peer (same ICE credentials and DTLS fingerprint). Voelin answered every offer +with a new peer, so the connection broke and nothing was shown. Now +`Peer::renegotiate` answers an `offer` signal on the running connection (a +`reconnectOffer` still starts a new one), in the codec order of the new offer +(str0m keeps the first offer's order; `order_like_offer` fixes the answer's +`m=` lines), so the streamer switches to the codec it re-offered. Tested +against Chromium: `browser_renegotiates_with_rust` (VP8, then a re-offer of +VP9 on the same connection; VP9 frames arrive). + ## Open questions - [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above). diff --git a/tests/interop/README.md b/tests/interop/README.md index 638c69a..d16948a 100644 --- a/tests/interop/README.md +++ b/tests/interop/README.md @@ -14,6 +14,7 @@ TeamSpeak server is involved. | `browser_streams_to_rust` | Chromium offers a canvas `captureStream` and an oscillator with VP8, VP9, H264 and AV1 preferred in turn (codecs the browser cannot send are skipped); our viewer `Peer::answer` must receive frames of that codec and Opus, over `AES_CM_128_HMAC_SHA1_80`. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe | | `real_encoders_decode_in_browser` (voelin-core) | Every encoder this machine has (`Codecs::encoders()`), as a share uses it: the 1280x720 test pattern through the `Streamer`, VA-API encoders also from DMA-BUFs as the ScreenCast portal hands over the screen; our streamer peer offers that codec alone (H.264 as Constrained Baseline, see below); the browser must decode at least 60 frames at 1280x720 in 3 s. Codecs the browser does not answer (HEVC, H.264 in Playwright's Chromium) are skipped | | `share_offer_picks_a_codec_every_client_decodes` (voelin-core) | The offer a share makes on this machine (`preferred_codec`, `peer_config`): the browser, answering with the first codec of the offer it lists as the official client does, must pick one every TeamSpeak client decodes (`decoded_everywhere`), and decode it | +| `browser_renegotiates_with_rust` | Chromium streams VP8, then sends a new offer on the same connection with VP9 first (as the official client re-offers when it does not encode the codec we chose); `Peer::renegotiate` answers on the same peer, in the new offer's codec order; VP9 frames must arrive | | `trickled_candidates_reach_browser` | A server-reflexive candidate (from a fake STUN server) as our sessions trickle it (`iceCandidate` signal with the peer's mid) is accepted by `addIceCandidate` | ## Running diff --git a/tests/interop/browser-peer.cjs b/tests/interop/browser-peer.cjs index 3ee84ff..e9f5a5b 100644 --- a/tests/interop/browser-peer.cjs +++ b/tests/interop/browser-peer.cjs @@ -7,6 +7,8 @@ // offer {codec, trickle} send canvas video + oscillator audio; offer with // `codec` preferred -> {sdp} or {unsupported}; // with `trickle` the SDP has no candidates +// reoffer {codec} a new offer on the running connection with `codec` +// preferred (a renegotiation) -> {sdp} or {unsupported} // candidates candidates gathered so far -> {candidates: [{candidate, sdpMid, sdpMLineIndex}]} // accept {sdp} apply the answer to our offer // candidate {candidate, sdpMid, sdpMLineIndex} add a remote candidate @@ -123,6 +125,19 @@ window.peer = { return { sdp }; }, + // A new offer on the running connection with the codec preferred, as the + // official client sends when it re-aligns its codec. + async reoffer({ codec }) { + const pc = this.pc; + const transceiver = pc.getTransceivers().find((t) => t.sender.track && t.sender.track.kind === 'video'); + const all = RTCRtpSender.getCapabilities('video').codecs; + const wanted = all.filter((c) => c.mimeType.toLowerCase() === 'video/' + codec.toLowerCase()); + if (wanted.length === 0) return { unsupported: codec }; + transceiver.setCodecPreferences([...wanted, ...all.filter((c) => !wanted.includes(c))]); + await pc.setLocalDescription(await pc.createOffer()); + return { sdp: pc.localDescription.sdp }; + }, + async candidates() { await gathered(this.pc, 3000); return { candidates: this.localCandidates };