tsc-stream: interop with Chromium's WebRTC stack, codec order fixes

tests/interop/browser-peer.cjs runs headless Chromium (Playwright) as the
remote peer; crates/tsc-stream/tests/browser_interop.rs (TSC_INTEROP=1)
exchanges SDP with it over stdin/stdout:

- our loopback streamer offer (VP8 + Opus) answered by Chromium: packets,
  bytes and decoded frames of the synthetic VP8 keyframes, Opus packets
- Chromium offers canvas video + oscillator audio with VP8, VP9, H264 and
  AV1 preferred in turn; our viewer peer receives that codec and Opus,
  with trickled browser candidates and a keyframe after a PLI
- a server-reflexive candidate (fake STUN server) trickled with the
  peer's mid is accepted by addIceCandidate

Fixes found on the way:
- the viewer's answer followed str0m's codec order, so the streamer's
  preference was ignored; the answer now keeps the offer's order
  (accept_video_codecs filters it)
- streamers offered VP8 and H264 by default while frames are sent on the
  first negotiated payload type: offer only VP8 by default
- H.264 offers include Constrained High (640c1f), reportedly the only
  profile the TeamSpeak client decodes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
Claude committed 2026-09-25 19:56:58 +00:00
1 parent a3969074fd
commit ee57b130c6
5 files changed
+698 -19

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
[dev-dependencies]
anyhow = "1"
futures = "0.3"
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] }
tokio = { version = "1", features = ["io-util", "macros", "net", "process", "rt-multi-thread", "sync", "time"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[lints]
+133 -18
View File
@@ -33,6 +33,8 @@ pub enum VideoCodec {
}
impl VideoCodec {
pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1];
pub fn from_codec(c: Codec) -> Option<Self> {
match c {
Codec::Vp8 => Some(Self::Vp8),
@@ -42,6 +44,20 @@ impl VideoCodec {
_ => None,
}
}
/// From an SDP encoding name (`a=rtpmap:<pt> VP8/90000`).
pub fn from_sdp_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.sdp_name().eq_ignore_ascii_case(name))
}
pub fn sdp_name(self) -> &'static str {
match self {
Self::Vp8 => "VP8",
Self::Vp9 => "VP9",
Self::H264 => "H264",
Self::Av1 => "AV1",
}
}
}
#[derive(Clone, Debug)]
@@ -50,8 +66,12 @@ pub struct PeerConfig {
pub hosts: Vec<IpAddr>,
/// STUN servers (`host:port`) for a server-reflexive candidate.
pub stun_servers: Vec<String>,
/// Video codecs, used for the streamer's offer; a viewer accepts all it knows.
/// Video codecs a streamer offers, in order of preference. Frames are sent
/// with the codec the viewer picks, so offer only what the encoder produces.
pub video_codecs: Vec<VideoCodec>,
/// Video codecs a viewer accepts (what it can decode). The answer keeps
/// the order of the streamer's offer, so the streamer's preference wins.
pub accept_video_codecs: Vec<VideoCodec>,
pub video: bool,
pub audio: bool,
}
@@ -61,7 +81,8 @@ impl Default for PeerConfig {
Self {
hosts: Vec::new(),
stun_servers: stun::TEAMSPEAK_STUN.iter().map(|s| (*s).to_owned()).collect(),
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264],
video_codecs: vec![VideoCodec::Vp8],
accept_video_codecs: VideoCodec::ALL.to_vec(),
video: true,
audio: true,
}
@@ -142,7 +163,7 @@ impl Peer {
/// Streamer side: create a connection that sends our media; returns the SDP
/// offer for `respondjoinstreamrequest`.
pub async fn offer(config: &PeerConfig, stream_id: &str) -> Result<(Self, String), PeerError> {
let mut rtc = build_rtc(config, true);
let mut rtc = build_rtc(config, &config.video_codecs);
let net = Net::bind(config, &mut rtc).await?;
let mut api = rtc.sdp_api();
let msid = Some(stream_id.to_owned());
@@ -163,8 +184,18 @@ impl Peer {
/// Viewer side: accept the streamer's offer; returns our SDP answer.
pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> {
// Our codecs in the order of the offer, then the rest.
let mut codecs: Vec<_> = offered_video_codecs(offer)
.into_iter()
.filter(|c| config.accept_video_codecs.contains(c))
.collect();
for c in &config.accept_video_codecs {
if !codecs.contains(c) {
codecs.push(*c);
}
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let mut rtc = build_rtc(config, false);
let mut rtc = build_rtc(config, &codecs);
let net = Net::bind(config, &mut rtc).await?;
let answer = rtc.sdp_api().accept_offer(offer)?;
Ok((Self::spawn(rtc, net, config, None, Vec::new()), answer.to_sdp_string()))
@@ -240,24 +271,66 @@ impl Drop for Peer {
}
}
fn build_rtc(config: &PeerConfig, offering: bool) -> Rtc {
let mut rtc_config =
RtcConfig::new().set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags()));
if offering {
// Offer only the codecs we can encode, in our order of preference.
rtc_config = rtc_config.clear_codecs().enable_opus(config.audio);
for codec in &config.video_codecs {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => rtc_config.enable_h264(true),
VideoCodec::Av1 => rtc_config.enable_av1(true),
};
}
/// H.264 Constrained High, level 3.1: reportedly the only H.264 profile the
/// TeamSpeak client decodes; str0m's defaults lack it.
const H264_CONSTRAINED_HIGH: u32 = 0x640c1f;
/// An RTC with Opus and `video` codecs, in this order of preference.
fn build_rtc(config: &PeerConfig, video: &[VideoCodec]) -> Rtc {
let mut rtc_config = RtcConfig::new()
.set_crypto_provider(Arc::new(str0m::crypto::from_feature_flags()))
.clear_codecs()
.enable_opus(config.audio);
for codec in video {
rtc_config = match codec {
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => {
let mut c = rtc_config.enable_h264(true);
c.codec_config().add_h264(
112.into(),
Some(113.into()),
true,
H264_CONSTRAINED_HIGH,
);
c
}
VideoCodec::Av1 => rtc_config.enable_av1(true),
};
}
rtc_config.build(Instant::now())
}
/// The video codecs of the first video media line of `sdp`, in offered order.
fn offered_video_codecs(sdp: &str) -> Vec<VideoCodec> {
let mut pts: Vec<&str> = Vec::new();
let mut names: Vec<(&str, VideoCodec)> = Vec::new();
let mut in_video = false;
for line in sdp.lines().map(str::trim) {
if let Some(media) = line.strip_prefix("m=") {
in_video = pts.is_empty() && media.starts_with("video ");
if in_video {
pts = media.split_whitespace().skip(3).collect();
}
} else if in_video
&& let Some((pt, encoding)) =
line.strip_prefix("a=rtpmap:").and_then(|r| r.split_once(' '))
&& let Some(codec) = encoding.split('/').next().and_then(VideoCodec::from_sdp_name)
{
names.push((pt, codec));
}
}
let mut codecs = Vec::new();
for pt in pts {
if let Some((_, codec)) = names.iter().find(|(p, _)| *p == pt)
&& !codecs.contains(codec)
{
codecs.push(*codec);
}
}
codecs
}
/// The primary local IPv4 address (the one used for the default route).
fn primary_ipv4() -> Option<IpAddr> {
let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
@@ -591,3 +664,45 @@ impl Task {
Some((mid, pt))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn offered_codec_order() {
let sdp = "v=0\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\
a=rtpmap:111 opus/48000/2\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 98 99 96 97 45 102\r\n\
a=rtpmap:96 VP8/90000\r\n\
a=rtpmap:97 rtx/90000\r\n\
a=rtpmap:98 VP9/90000\r\n\
a=rtpmap:99 rtx/90000\r\n\
a=rtpmap:45 AV1/90000\r\n\
a=rtpmap:102 H264/90000\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
a=rtpmap:96 H264/90000\r\n";
assert_eq!(
offered_video_codecs(sdp),
[VideoCodec::Vp9, VideoCodec::Vp8, VideoCodec::Av1, VideoCodec::H264]
);
assert!(offered_video_codecs("v=0\r\n").is_empty());
}
#[tokio::test]
async fn answer_follows_offer_order() {
let streamer = PeerConfig {
video_codecs: vec![VideoCodec::H264, VideoCodec::Vp8],
..PeerConfig::loopback()
};
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
let vp8_only =
PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() };
let (_peer, answer) = Peer::answer(&vp8_only, &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
}
}
+320
View File
@@ -0,0 +1,320 @@
//! Interop with a browser WebRTC stack: headless Chromium (Playwright) is the
//! other peer, driven by `tests/interop/browser-peer.cjs` over stdin/stdout.
//! No TeamSpeak server is involved; SDP goes straight between the peers.
//!
//! Runs only with `TSC_INTEROP=1` (see `tests/interop/README.md`).
use std::path::PathBuf;
use std::process::Stdio;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::time::timeout;
use tsc_stream::{
Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SyntheticSource,
};
fn enabled() -> bool {
std::env::var("TSC_INTEROP").is_ok_and(|v| v == "1")
}
/// The Node.js side (headless Chromium).
struct Browser {
_child: Child,
stdin: ChildStdin,
stdout: Lines<BufReader<ChildStdout>>,
}
impl Browser {
async fn start() -> Self {
let script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/interop/browser-peer.cjs")
.canonicalize()
.expect("tests/interop/browser-peer.cjs");
let node = std::env::var("TSC_NODE").unwrap_or_else(|_| "node".into());
let mut command = Command::new(node);
command
.arg(script)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
// Playwright is usually installed globally.
if std::env::var_os("NODE_PATH").is_none()
&& let Ok(out) = std::process::Command::new("npm").args(["root", "-g"]).output()
{
command.env("NODE_PATH", String::from_utf8_lossy(&out.stdout).trim());
}
let mut child = command.spawn().expect("cannot start node (set TSC_NODE)");
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap()).lines();
let mut browser = Self { _child: child, stdin, stdout };
let ready = browser.read().await;
eprintln!("browser: {}", ready["userAgent"]);
browser
}
async fn read(&mut self) -> Value {
let line = timeout(Duration::from_secs(60), self.stdout.next_line())
.await
.expect("browser did not answer")
.unwrap()
.expect("browser exited");
let value: Value = serde_json::from_str(&line).unwrap();
if let Some(error) = value.get("error") {
panic!("browser: {error}");
}
value
}
async fn call(&mut self, command: Value) -> Value {
let mut line = command.to_string();
line.push('\n');
self.stdin.write_all(line.as_bytes()).await.unwrap();
self.read().await
}
async fn quit(mut self) {
let _ = self.call(json!({ "op": "quit" })).await;
}
}
async fn wait_connected(peer: &mut Peer) {
timeout(Duration::from_secs(15), async {
loop {
match peer.next_event().await {
Some(PeerEvent::Connected) => return,
Some(PeerEvent::Closed) | None => panic!("closed before connecting"),
_ => {}
}
}
})
.await
.expect("no connection with the browser");
}
/// Our streamer peer (as in a TeamSpeak stream) sends VP8 + Opus to Chromium.
#[tokio::test(flavor = "multi_thread")]
async fn rust_streams_to_browser() {
if !enabled() {
eprintln!("skipped: set TSC_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 config = PeerConfig::loopback();
let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap();
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
let answer = answer["sdp"].as_str().unwrap();
eprintln!("browser answer:\n{answer}");
peer.accept_answer(answer).await.unwrap();
wait_connected(&mut peer).await;
// Three seconds of synthetic media.
let mut source = SyntheticSource::new(30, 3000, true);
let mut frames = Vec::new();
let mut keyframe_requests = 0;
let end = Instant::now() + Duration::from_secs(3);
while Instant::now() < end {
source.poll_frames(Instant::now(), &mut frames);
for f in frames.drain(..) {
peer.write(f.kind, f.time, f.data);
}
while let Some(event) = peer.try_next_event() {
if let PeerEvent::KeyframeRequest = event {
keyframe_requests += 1;
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stats = browser.call(json!({ "op": "stats" })).await;
eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}");
assert_eq!(stats["connectionState"], "connected");
let video = &stats["inbound"]["video"];
let audio = &stats["inbound"]["audio"];
assert_eq!(video["codec"], "video/VP8");
assert!(video["packetsReceived"].as_u64().unwrap() > 100, "video packets: {video}");
assert!(video["bytesReceived"].as_u64().unwrap() > 100_000, "video bytes: {video}");
assert_eq!(audio["codec"], "audio/opus");
assert!(audio["packetsReceived"].as_u64().unwrap() > 50, "audio packets: {audio}");
// The synthetic frames are real (tiny) VP8 keyframes.
assert!(video["framesDecoded"].as_u64().unwrap() > 30, "decoded: {video}");
browser.quit().await;
}
/// Answer STUN binding requests with a made-up public address, so a peer
/// reports a server-reflexive candidate without internet access.
async fn fake_stun_server() -> std::net::SocketAddr {
let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let addr = socket.local_addr().unwrap();
tokio::spawn(async move {
let mut buf = [0; 1500];
while let Ok((n, from)) = socket.recv_from(&mut buf).await {
if n < 20 || buf[..2] != [0, 1] {
continue;
}
// Binding success with XOR-MAPPED-ADDRESS 203.0.113.9:40000.
let mut resp = vec![0x01, 0x01, 0, 12];
resp.extend_from_slice(&buf[4..20]);
resp.extend_from_slice(&[0, 0x20, 0, 8, 0, 1]);
resp.extend_from_slice(&(40000u16 ^ 0x2112).to_be_bytes());
let ip = u32::from(std::net::Ipv4Addr::new(203, 0, 113, 9)) ^ 0x2112_A442;
resp.extend_from_slice(&ip.to_be_bytes());
let _ = socket.send_to(&resp, from).await;
}
});
addr
}
/// A trickled candidate as our sessions send it (`iceCandidate` signal with
/// the peer's mid) must be accepted by the browser.
#[tokio::test(flavor = "multi_thread")]
async fn trickled_candidates_reach_browser() {
if !enabled() {
eprintln!("skipped: set TSC_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let mut browser = Browser::start().await;
// Primary address (STUN is not sent from loopback) and the fake STUN server.
let stun = fake_stun_server().await;
let config = PeerConfig {
hosts: Vec::new(),
stun_servers: vec![stun.to_string()],
..PeerConfig::loopback()
};
let (mut peer, offer) = Peer::offer(&config, "interop").await.unwrap();
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
peer.accept_answer(answer["sdp"].as_str().unwrap()).await.unwrap();
let (candidate, mid) = timeout(Duration::from_secs(10), async {
loop {
match peer.next_event().await {
Some(PeerEvent::LocalCandidate { candidate, mid }) => return (candidate, mid),
Some(PeerEvent::Closed) | None => panic!("closed"),
_ => {}
}
}
})
.await
.expect("no server-reflexive candidate");
assert!(candidate.contains("203.0.113.9 40000 typ srflx"), "{candidate}");
let first_mid = offer.lines().find_map(|l| l.strip_prefix("a=mid:")).unwrap().trim();
assert_eq!(mid.as_deref(), Some(first_mid));
// Through the signal JSON, as the server relays it.
let json = Signal::IceCandidate { candidate, mid, mline_index: Some(0) }.to_json();
let Signal::IceCandidate { candidate, mid, mline_index } = Signal::parse(&json).unwrap() else {
unreachable!()
};
let add = json!({
"op": "candidate", "candidate": candidate, "sdpMid": mid, "sdpMLineIndex": mline_index
});
browser.call(add).await;
wait_connected(&mut peer).await;
browser.quit().await;
}
/// Frames per codec.
#[derive(Debug, Default)]
struct Counts(Vec<(Codec, usize)>);
impl Counts {
fn add(&mut self, codec: Codec) {
match self.0.iter_mut().find(|(c, _)| *c == codec) {
Some((_, n)) => *n += 1,
None => self.0.push((codec, 1)),
}
}
fn get(&self, codec: Codec) -> usize {
self.0.iter().find(|(c, _)| *c == codec).map_or(0, |(_, n)| *n)
}
fn total(&self) -> usize {
self.0.iter().map(|(_, n)| n).sum()
}
}
struct Received {
video: Counts,
audio: Counts,
/// VP8 keyframes (frame tag bit 0 clear).
vp8_keyframes: usize,
}
/// Collect frames from `peer` for up to `limit` or until `enough`.
async fn receive(peer: &mut Peer, limit: Duration, enough: usize) -> Received {
let mut r = Received { video: Counts::default(), audio: Counts::default(), vp8_keyframes: 0 };
let _ = timeout(limit, async {
while let Some(event) = peer.next_event().await {
if let PeerEvent::Media(frame) = event {
let map = match frame.kind {
MediaKind::Video => &mut r.video,
MediaKind::Audio => &mut r.audio,
};
map.add(frame.codec);
if frame.codec == Codec::Vp8 && frame.data.first().is_some_and(|b| b & 1 == 0) {
r.vp8_keyframes += 1;
}
if r.video.total() >= enough && r.audio.total() >= enough {
return;
}
}
}
})
.await;
r
}
/// Chromium sends a canvas stream and an oscillator; our viewer peer answers.
#[tokio::test(flavor = "multi_thread")]
async fn browser_streams_to_rust() {
if !enabled() {
eprintln!("skipped: set TSC_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 config = PeerConfig::loopback();
let mut tested = Vec::new();
for (name, codec) in
[("VP8", Codec::Vp8), ("VP9", Codec::Vp9), ("H264", Codec::H264), ("AV1", Codec::Av1)]
{
// VP8 with trickled browser candidates, the others with candidates in the SDP.
let trickle = codec == Codec::Vp8;
let offer = browser.call(json!({ "op": "offer", "codec": name, "trickle": trickle })).await;
if offer.get("unsupported").is_some() {
eprintln!("{name}: the browser cannot send it, skipped");
continue;
}
let offer = offer["sdp"].as_str().unwrap();
let (mut peer, answer) = Peer::answer(&config, offer).await.unwrap();
browser.call(json!({ "op": "accept", "sdp": answer })).await;
if trickle {
let candidates = browser.call(json!({ "op": "candidates" })).await;
let candidates = candidates["candidates"].as_array().unwrap();
assert!(!candidates.is_empty(), "no browser candidates");
for c in candidates {
peer.add_remote_candidate(c["candidate"].as_str().unwrap());
}
}
wait_connected(&mut peer).await;
let received = receive(&mut peer, Duration::from_secs(8), 60).await;
eprintln!(
"{name}: video {:?}, audio {:?}, VP8 keyframes {}",
received.video, received.audio, received.vp8_keyframes
);
assert!(received.video.get(codec) >= 30, "{name} video frames");
assert!(received.audio.get(Codec::Opus) >= 30, "{name} Opus frames");
if codec == Codec::Vp8 {
// A keyframe request (PLI) makes the browser's encoder send one.
let before = received.vp8_keyframes;
peer.request_keyframe();
let after = receive(&mut peer, Duration::from_secs(3), 90).await;
assert!(after.vp8_keyframes > 0, "no keyframe after PLI (had {before} before)");
}
tested.push(name);
}
assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}");
browser.quit().await;
}
+46
View File
@@ -0,0 +1,46 @@
# Browser interop test
`crates/tsc-stream/tests/browser_interop.rs` checks our str0m peers against
the WebRTC stack of Chromium (libwebrtc, the same stack as the official
TeamSpeak 6 client). `browser-peer.cjs` runs headless Chromium through
Playwright and exchanges SDP and candidates with the Rust test as JSON lines
on stdin/stdout. No TeamSpeak server is involved.
| Test | What it checks |
|---|---|
| `rust_streams_to_browser` | Our streamer offer (`PeerConfig::loopback()`, VP8 + Opus) answered by an `RTCPeerConnection`; `SyntheticSource` media for 3 s; `inbound-rtp` stats: VP8 packets and bytes, decoded frames (the synthetic frames are real 1x1 VP8 keyframes), Opus packets |
| `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. VP8 also uses trickled browser candidates and checks that a PLI brings a keyframe |
| `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
Needs Node.js with Playwright and its Chromium (`npx playwright install
chromium` on a new machine; `PLAYWRIGHT_BROWSERS_PATH` if the browsers live
elsewhere).
```sh
TSC_INTEROP=1 cargo test -p tsc-stream --test browser_interop -- --nocapture
```
Without `TSC_INTEROP=1` the tests return immediately, so `cargo test` passes on
machines without a browser. `TSC_NODE` selects the node binary; `NODE_PATH`
defaults to `npm root -g` so a global Playwright is found.
Chromium is started with `--disable-features=WebRtcHideLocalIpsWithMdns`:
without camera/microphone permission it would hide host candidates behind
mDNS names (`<uuid>.local`), which str0m cannot resolve. The official client
may do the same; see `docs/protocol-notes/ts6-streaming.md`.
## Findings
- Chromium 141 (Playwright 1.56) connects to a str0m peer on 127.0.0.1 from its
own host candidate on the primary interface; it gathers no loopback candidates.
- str0m's answer lists codecs in its own configured order, and the offerer
sends the first one. `Peer::answer` therefore configures the viewer's codecs
in the order of the offer (`accept_video_codecs` filters them).
- `Peer::write` sends on the first negotiated payload type of a kind, so a
streamer offers only the codecs its encoder produces (`video_codecs`,
default VP8 only).
- str0m mids are random strings (`a=mid:fhs`), not `0`/`1`; trickled
candidates must carry the real mid, or browsers reject them.
- Playwright's Chromium build sends VP8, VP9 and AV1, not H.264.
+198
View File
@@ -0,0 +1,198 @@
// Headless Chromium as the remote WebRTC peer for
// crates/tsc-stream/tests/browser_interop.rs (see README.md here).
//
// Reads one JSON command per line on stdin and writes one JSON reply per line
// on stdout; logs go to stderr. Commands (`op`):
// answer {sdp} answer an offer, wait for ICE gathering -> {sdp}
// offer {codec, trickle} send canvas video + oscillator audio; offer with
// `codec` preferred -> {sdp} or {unsupported};
// with `trickle` the SDP has no candidates
// 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
// stats connection state, inbound/outbound RTP counters,
// frames shown by a <video> element
// quit
'use strict';
const readline = require('node:readline');
const { chromium } = require('playwright');
// Runs in the page.
const PAGE_SCRIPT = `
function gathered(pc, ms) {
return new Promise((resolve) => {
if (pc.iceGatheringState === 'complete') return resolve();
pc.addEventListener('icegatheringstatechange', () => {
if (pc.iceGatheringState === 'complete') resolve();
});
setTimeout(resolve, ms);
});
}
window.peer = {
pc: null,
timers: [],
shownFrames: 0,
localCandidates: [],
reset() {
if (this.pc) this.pc.close();
this.timers.forEach(clearInterval);
this.timers = [];
this.shownFrames = 0;
this.localCandidates = [];
this.pc = new RTCPeerConnection();
this.pc.addEventListener('icecandidate', (e) => {
if (e.candidate && e.candidate.candidate) this.localCandidates.push(e.candidate.toJSON());
});
this.pc.addEventListener('connectionstatechange', () => {
console.log('connection ' + this.pc.connectionState);
});
return this.pc;
},
// Count frames a <video> element actually presents (needs decodable video).
show(track) {
const video = document.createElement('video');
video.muted = true;
video.autoplay = true;
video.srcObject = new MediaStream([track]);
document.body.appendChild(video);
const count = () => {
this.shownFrames++;
video.requestVideoFrameCallback(count);
};
video.requestVideoFrameCallback(count);
video.play().catch((e) => console.log('play: ' + e));
},
async answer({ sdp }) {
const pc = this.reset();
pc.addEventListener('track', (e) => {
if (e.track.kind === 'video') this.show(e.track);
});
await pc.setRemoteDescription({ type: 'offer', sdp });
await pc.setLocalDescription(await pc.createAnswer());
await gathered(pc, 3000);
return { sdp: pc.localDescription.sdp };
},
async offer({ codec, trickle }) {
const pc = this.reset();
const canvas = document.createElement('canvas');
canvas.width = 320;
canvas.height = 240;
const ctx = canvas.getContext('2d');
let n = 0;
this.timers.push(setInterval(() => {
n++;
ctx.fillStyle = 'hsl(' + ((n * 7) % 360) + ',60%,50%)';
ctx.fillRect(0, 0, 320, 240);
ctx.fillStyle = '#fff';
ctx.fillText(String(n), 10 + (n % 200), 20 + (n % 150));
}, 33));
const video = canvas.captureStream(30).getVideoTracks()[0];
const audioCtx = new AudioContext();
const osc = audioCtx.createOscillator();
const dest = audioCtx.createMediaStreamDestination();
osc.connect(dest);
osc.start();
const audio = dest.stream.getAudioTracks()[0];
const stream = new MediaStream([video, audio]);
const transceiver = pc.addTransceiver(video, { direction: 'sendonly', streams: [stream] });
pc.addTransceiver(audio, { direction: 'sendonly', streams: [stream] });
if (codec) {
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());
if (!trickle) await gathered(pc, 3000);
const sdp = trickle ? pc.localDescription.sdp.split('\\r\\n').filter((l) => !l.startsWith('a=candidate')).join('\\r\\n') : pc.localDescription.sdp;
return { sdp };
},
async candidates() {
await gathered(this.pc, 3000);
return { candidates: this.localCandidates };
},
async accept({ sdp }) {
await this.pc.setRemoteDescription({ type: 'answer', sdp });
return { ok: true };
},
async candidate({ candidate, sdpMid, sdpMLineIndex }) {
await this.pc.addIceCandidate({ candidate, sdpMid, sdpMLineIndex });
return { ok: true };
},
async stats() {
const report = await this.pc.getStats();
const codecs = {};
const inbound = {};
const outbound = {};
report.forEach((s) => {
if (s.type === 'codec') codecs[s.id] = s.mimeType;
if (s.type === 'inbound-rtp') inbound[s.kind] = s;
if (s.type === 'outbound-rtp') outbound[s.kind] = s;
});
const pick = (s, keys) => {
const o = { codec: codecs[s.codecId] };
keys.forEach((k) => (o[k] = s[k]));
return o;
};
const out = { connectionState: this.pc.connectionState, shownFrames: this.shownFrames, inbound: {}, outbound: {} };
for (const k in inbound) {
out.inbound[k] = pick(inbound[k], ['packetsReceived', 'bytesReceived', 'packetsLost', 'framesReceived', 'framesDecoded', 'keyFramesDecoded', 'pliCount', 'totalSamplesReceived']);
}
for (const k in outbound) {
out.outbound[k] = pick(outbound[k], ['packetsSent', 'bytesSent', 'framesEncoded', 'keyFramesEncoded', 'pliCount']);
}
return out;
},
async quit() {
if (this.pc) this.pc.close();
return { ok: true };
},
};
`;
async function main() {
const browser = await chromium.launch({
headless: true,
args: [
// Real host candidates instead of mDNS names (no getUserMedia permission here).
'--disable-features=WebRtcHideLocalIpsWithMdns',
'--autoplay-policy=no-user-gesture-required',
],
});
const page = await browser.newPage();
page.on('console', (m) => process.stderr.write('[page] ' + m.text() + '\n'));
await page.setContent('<!doctype html><html><body></body></html>');
await page.addScriptTag({ content: PAGE_SCRIPT });
process.stdout.write(JSON.stringify({ ready: true, userAgent: await page.evaluate(() => navigator.userAgent) }) + '\n');
const lines = readline.createInterface({ input: process.stdin });
for await (const line of lines) {
if (!line.trim()) continue;
const cmd = JSON.parse(line);
let reply;
try {
reply = await page.evaluate(([op, arg]) => window.peer[op](arg), [cmd.op, cmd]);
} catch (e) {
reply = { error: String(e) };
}
process.stdout.write(JSON.stringify(reply) + '\n');
if (cmd.op === 'quit') break;
}
await browser.close();
}
main().catch((e) => {
process.stderr.write(String(e && e.stack ? e.stack : e) + '\n');
process.exit(1);
});