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:
1 parent
8d8a8c5eab
commit
23fbbf0221
5 files changed
+698
-19
No files matched your search
@@ -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.
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user