Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a33c34a3879196dbf
This commit is contained in:
commit
f2ffd761fc
14 files changed
+440
-122
No files matched your search
@@ -51,7 +51,8 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
|
||||
tsproto-types = { path = "../proto/tsproto-types" }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] }
|
||||
# `process`: the browser interop test drives Chromium through Node.js.
|
||||
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -142,29 +142,37 @@ pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig {
|
||||
config
|
||||
}
|
||||
|
||||
/// Whether every official TeamSpeak client decodes `codec`: their WebRTC
|
||||
/// stack has VP8, VP9 and AV1 decoders built in. H.264 needs an OpenH264
|
||||
/// library the official client downloads at start-up and may not get; it
|
||||
/// still answers H.264 then, and decodes nothing (libwebrtc's
|
||||
/// `NullVideoDecoder`). HEVC needs a hardware decoder.
|
||||
pub fn decoded_everywhere(codec: Codec) -> bool {
|
||||
matches!(codec, Codec::Vp8 | Codec::Vp9 | Codec::Av1)
|
||||
}
|
||||
|
||||
/// What a streamer with `primary` as its stream codec offers, in order:
|
||||
/// `primary`, the codecs of hardware encoders, VP8 through libvpx (every
|
||||
/// TeamSpeak client decodes it), and HEVC last (for peers that take nothing
|
||||
/// else). Other software encoders are only ever the stream codec, so no
|
||||
/// viewer's answer starts one of them on top of it.
|
||||
/// `primary`; the codecs of hardware encoders and VP8 through libvpx that
|
||||
/// every TeamSpeak client decodes ([`decoded_everywhere`]), so that a
|
||||
/// viewer, which answers with the first codec it supports, never picks
|
||||
/// H.264 while one of them is there; H.264 from hardware; HEVC last (for
|
||||
/// peers that take nothing else). Other software encoders are only ever the
|
||||
/// stream codec, so no viewer's answer starts one of them on top of it.
|
||||
pub fn offer_codecs(codecs: &Codecs, primary: Codec) -> Vec<Codec> {
|
||||
let mut offer = vec![primary];
|
||||
let mut hevc = false;
|
||||
for (codec, backend) in codecs.encoders() {
|
||||
let cheap = codecs.is_hardware(backend)
|
||||
|| (codec == Codec::Vp8 && backend == voelin_media::EncoderBackend::Libvpx);
|
||||
if !cheap || offer.contains(&codec) {
|
||||
continue;
|
||||
}
|
||||
if codec == Codec::H265 {
|
||||
hevc = true;
|
||||
} else {
|
||||
if cheap && !offer.contains(&codec) {
|
||||
offer.push(codec);
|
||||
}
|
||||
}
|
||||
if hevc && primary != Codec::H265 {
|
||||
offer.push(Codec::H265);
|
||||
}
|
||||
// Stable: the encoder preference orders codecs of the same rank.
|
||||
offer[1..].sort_by_key(|&codec| match codec {
|
||||
_ if decoded_everywhere(codec) => 0,
|
||||
Codec::H265 => 2,
|
||||
_ => 1,
|
||||
});
|
||||
offer
|
||||
}
|
||||
|
||||
@@ -180,12 +188,14 @@ pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media:
|
||||
|
||||
/// The stream codec: `configured` if we can encode it, else the first codec
|
||||
/// of the encoder preference (hardware first when enabled; VP8 through
|
||||
/// libvpx without hardware), never HEVC (offered last only). Put it first in
|
||||
/// `PeerConfig::video_codecs` before [`peer_config`].
|
||||
/// libvpx without hardware) that every TeamSpeak client decodes
|
||||
/// ([`decoded_everywhere`]), else any but HEVC (offered last only). Put it
|
||||
/// first in `PeerConfig::video_codecs` before [`peer_config`].
|
||||
pub fn preferred_codec(codecs: &Codecs, configured: Option<Codec>) -> Option<Codec> {
|
||||
let encodable = codecs.encoder_codecs();
|
||||
configured
|
||||
.filter(|c| encodable.contains(c))
|
||||
.or_else(|| encodable.iter().copied().find(|&c| decoded_everywhere(c)))
|
||||
.or_else(|| encodable.into_iter().find(|c| *c != Codec::H265))
|
||||
}
|
||||
|
||||
@@ -2827,6 +2837,21 @@ mod tests {
|
||||
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
|
||||
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
|
||||
}
|
||||
// Whatever this machine has: codecs every TeamSpeak client decodes
|
||||
// come before H.264, HEVC last, and the automatic stream codec is
|
||||
// one of the first.
|
||||
let rank = |c: &Codec| match c {
|
||||
_ if decoded_everywhere(*c) => 0,
|
||||
Codec::H265 => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
|
||||
assert!(ranks.is_sorted(), "{offer:?}");
|
||||
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
|
||||
assert_eq!(
|
||||
preferred_codec(&all, Some(Codec::H264)).is_some(),
|
||||
all.encoder_codecs().contains(&Codec::H264)
|
||||
);
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
|
||||
@@ -964,7 +964,8 @@ pub enum CodecChoice {
|
||||
pub static STREAM_CODEC: Key<CodecChoice> = Key::new(
|
||||
"stream.codec",
|
||||
Kind::Choice(&["auto", "vp8", "vp9", "h264", "av1"]),
|
||||
"Video codec of our stream.",
|
||||
"Video codec of our stream. Official TeamSpeak clients always decode VP8, VP9 and AV1; \
|
||||
H.264 only when they could download OpenH264.",
|
||||
CodecChoice::default,
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
//! The stream's real encoders against a browser's WebRTC stack: the test
|
||||
//! pattern, encoded by each encoder this machine has as a share encodes the
|
||||
//! screen, sent by our streamer peer offering just that codec, must decode
|
||||
//! at its size in headless Chromium (libwebrtc, the stack the official
|
||||
//! TeamSpeak 6 client is built on).
|
||||
//!
|
||||
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
|
||||
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
|
||||
//! skipped; `VOELIN_CHROMIUM=/usr/bin/chromium` tests a system Chromium that
|
||||
//! decodes H.264.
|
||||
|
||||
#![cfg(feature = "media-desktop")]
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use tokio::time::timeout;
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs};
|
||||
use voelin_core::media::{
|
||||
EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec,
|
||||
peer_config, preferred_codec, video_codec,
|
||||
};
|
||||
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
|
||||
use voelin_stream::{Peer, PeerEvent};
|
||||
|
||||
#[path = "../../../tests/interop/browser.rs"]
|
||||
mod browser;
|
||||
use browser::{Browser, enabled};
|
||||
|
||||
const SIZE: (u32, u32) = (1280, 720);
|
||||
|
||||
/// The test pattern encoded with `codec` by the encoders `preference` picks
|
||||
/// (from DMA-BUFs with `dmabuf`, as the ScreenCast portal hands over the
|
||||
/// screen).
|
||||
async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool) -> EncodedSource {
|
||||
let codecs = Codecs::new().with_preference(preference.clone());
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
synthetic_size: SIZE,
|
||||
synthetic_dmabuf: dmabuf,
|
||||
fps: 30,
|
||||
bitrate_kbps: 3000,
|
||||
audio: false,
|
||||
codec,
|
||||
encoder: preference,
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
EncodedSource::new(Streamer::start(&codecs, config).await.unwrap())
|
||||
}
|
||||
|
||||
/// Our streamer peer with `config`'s offer, answered by the browser and
|
||||
/// connected; the codec the answer chose, `None` if it took no video.
|
||||
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoCodec)> {
|
||||
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.ok()?;
|
||||
let mut chosen = None;
|
||||
timeout(Duration::from_secs(15), async {
|
||||
loop {
|
||||
match peer.next_event().await {
|
||||
Some(PeerEvent::VideoCodec(codec)) => chosen = Some(codec),
|
||||
Some(PeerEvent::Connected) => return,
|
||||
Some(PeerEvent::Closed) | None => panic!("closed before connecting"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("no connection with the browser");
|
||||
Some((peer, chosen?))
|
||||
}
|
||||
|
||||
/// Three seconds of `source` to `peer`; the browser's `inbound-rtp` video
|
||||
/// stats.
|
||||
async fn send(browser: &mut Browser, peer: &mut Peer, source: &mut EncodedSource) -> Value {
|
||||
source.request_keyframe();
|
||||
let mut frames = Vec::new();
|
||||
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 matches!(event, PeerEvent::KeyframeRequest) {
|
||||
source.request_keyframe();
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
peer.close();
|
||||
stats["inbound"]["video"].clone()
|
||||
}
|
||||
|
||||
/// Whether the browser decoded most of three seconds at the stream's size.
|
||||
fn decoded(video: &Value) -> Result<(), String> {
|
||||
let frames = video["framesDecoded"].as_u64().unwrap_or(0);
|
||||
let size = (video["frameWidth"].as_u64(), video["frameHeight"].as_u64());
|
||||
let expected = (Some(u64::from(SIZE.0)), Some(u64::from(SIZE.1)));
|
||||
if frames < 60 || size != expected {
|
||||
return Err(format!("{frames} frames decoded at {size:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every encoder of this machine (hardware ones from memory and from
|
||||
/// DMA-BUFs) decodes in the browser: most frames decoded, at the stream's
|
||||
/// size.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn real_encoders_decode_in_browser() {
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let mut browser = Browser::start().await;
|
||||
let codecs = Codecs::new();
|
||||
let udmabuf = std::path::Path::new("/dev/udmabuf").exists();
|
||||
let mut failed = Vec::new();
|
||||
for (codec, backend) in codecs.encoders() {
|
||||
let gpu = codecs.is_hardware(backend) && backend.name().ends_with("_vaapi") && udmabuf;
|
||||
for dmabuf in [false, true].into_iter().filter(|d| !d || gpu) {
|
||||
let what =
|
||||
format!("{codec} {}{}", backend.name(), if dmabuf { " (DMA-BUF)" } else { "" });
|
||||
let config = PeerConfig {
|
||||
video_codecs: vec![video_codec(codec)],
|
||||
audio: false,
|
||||
// Headless Chromium lists only the H.264 profiles of
|
||||
// libwebrtc's software decoder (Baseline, Constrained
|
||||
// Baseline, Main), not the Constrained High we offer; its
|
||||
// FFmpeg decoder takes our High profile streams all the same.
|
||||
h264_profile_level_id: 0x42e01f,
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let Some((mut peer, _)) = connect(&mut browser, &config).await else {
|
||||
eprintln!("{what}: the browser does not decode it, skipped");
|
||||
continue;
|
||||
};
|
||||
let preference =
|
||||
EncoderPreference { hardware: true, backend: backend.name().parse().unwrap() };
|
||||
let mut source = test_pattern(preference, codec, dmabuf).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
eprintln!("{what}: {video}");
|
||||
if let Err(e) = decoded(&video) {
|
||||
failed.push(format!("{what}: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
browser.quit().await;
|
||||
assert!(failed.is_empty(), "not decoded in the browser:\n{}", failed.join("\n"));
|
||||
}
|
||||
|
||||
/// The offer a share makes on this machine (`preferred_codec`,
|
||||
/// `peer_config`): the browser, which answers like the official client with
|
||||
/// the first codec of the offer it lists, picks one every TeamSpeak client
|
||||
/// decodes, never H.264 ahead of them (the official client may list H.264
|
||||
/// without being able to decode it), and decodes it.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn share_offer_picks_a_codec_every_client_decodes() {
|
||||
if !enabled() {
|
||||
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
|
||||
return;
|
||||
}
|
||||
let mut browser = Browser::start().await;
|
||||
let codecs = Codecs::new();
|
||||
let primary = preferred_codec(&codecs, None).expect("an encoder");
|
||||
let config = PeerConfig {
|
||||
video_codecs: vec![video_codec(primary)],
|
||||
audio: false,
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
let config = peer_config(&codecs, config);
|
||||
eprintln!("offer: {:?}", config.video_codecs);
|
||||
let (mut peer, chosen) = connect(&mut browser, &config).await.expect("video answered");
|
||||
let chosen = media_codec(chosen);
|
||||
assert!(
|
||||
decoded_everywhere(chosen),
|
||||
"the browser chose {chosen} from {:?}",
|
||||
config.video_codecs
|
||||
);
|
||||
let mut source = test_pattern(codecs.preference().clone(), chosen, false).await;
|
||||
let video = send(&mut browser, &mut peer, &mut source).await;
|
||||
eprintln!("{chosen}: {video}");
|
||||
browser.quit().await;
|
||||
decoded(&video).unwrap();
|
||||
}
|
||||
@@ -9,7 +9,9 @@
|
||||
//! disable it (see docs/media.md).
|
||||
//!
|
||||
//! TeamSpeak clients only decode H.264 Constrained High; OpenH264 encodes
|
||||
//! without B-frames, so its High profile output qualifies.
|
||||
//! without B-frames, so its High profile output qualifies. The official
|
||||
//! client decodes H.264 only once it downloaded OpenH264 itself, so streams
|
||||
//! prefer codecs it always decodes (`voelin_core::media::decoded_everywhere`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
||||
@@ -406,10 +406,12 @@ fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
|
||||
Error::CodecUnavailable { codec, reason: reason.into() }
|
||||
}
|
||||
|
||||
/// Order of codecs among hardware encoders: H.264 (every viewer decodes
|
||||
/// it), AV1, VP9, VP8, and HEVC last (only for peers that take nothing
|
||||
/// else).
|
||||
const HARDWARE_ORDER: [Codec; 5] = [Codec::H264, Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H265];
|
||||
/// Order of codecs among hardware encoders: the ones every TeamSpeak
|
||||
/// client decodes first (AV1, VP9, VP8: the official client's WebRTC stack
|
||||
/// has their decoders built in), then H.264 (the official client decodes it
|
||||
/// only with an OpenH264 library it downloads at start-up and may not get),
|
||||
/// and HEVC last (only for peers that take nothing else).
|
||||
const HARDWARE_ORDER: [Codec; 5] = [Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H264, Codec::H265];
|
||||
|
||||
/// An encoder backend in the base order (before the preference applies).
|
||||
struct Candidate {
|
||||
@@ -868,8 +870,8 @@ mod tests {
|
||||
codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect()
|
||||
};
|
||||
let auto = names(EncoderPreference::default());
|
||||
// Hardware in codec order (HEVC last), then software.
|
||||
assert_eq!(auto[..3], ["h264_gpu", "vp8_gpu", "hevc_gpu"]);
|
||||
// Hardware in codec order (H.264 after VP8, HEVC last), then software.
|
||||
assert_eq!(auto[..3], ["vp8_gpu", "h264_gpu", "hevc_gpu"]);
|
||||
let position = |list: &[&str], name| list.iter().position(|n| *n == name).unwrap();
|
||||
assert!(position(&auto, "x264") < position(&auto, "av1_sw"));
|
||||
#[cfg(feature = "vpx")]
|
||||
@@ -886,7 +888,7 @@ mod tests {
|
||||
assert!(!named[1..].iter().any(|n| n.ends_with("_gpu")));
|
||||
// The codecs follow the preference.
|
||||
codecs.set_preference(EncoderPreference::default());
|
||||
assert_eq!(codecs.encoder_codecs()[..3], [Codec::H264, Codec::Vp8, Codec::H265]);
|
||||
assert_eq!(codecs.encoder_codecs()[..3], [Codec::Vp8, Codec::H264, Codec::H265]);
|
||||
// The report ranks what the preference uses.
|
||||
let report = codecs.report();
|
||||
let openh264 = report.encoders.iter().find(|e| e.name == "openh264").unwrap();
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//! (MIT-SHM and GetImage), checks pixels, and sends a window capture through
|
||||
//! VP8 and back.
|
||||
//!
|
||||
//! Needs `DISPLAY` (e.g. `Xvfb :101 -screen 0 1280x720x24 & DISPLAY=:101
|
||||
//! cargo test -p voelin-media --test x11_capture`); skipped without it.
|
||||
//! Needs a test X server in `VOELIN_X11_TEST_DISPLAY`, never the desktop's
|
||||
//! `DISPLAY` (it maps windows and moves the pointer): e.g. `xvfb-run -a bash
|
||||
//! -c 'VOELIN_X11_TEST_DISPLAY=$DISPLAY cargo test -p voelin-media --test
|
||||
//! x11_capture'`, as CI does; skipped without it.
|
||||
#![cfg(all(target_os = "linux", feature = "x11", feature = "vpx"))]
|
||||
|
||||
use std::time::Duration;
|
||||
@@ -150,8 +152,9 @@ async fn check_monitor(capture: &mut X11Capture, scene: &Scene) {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn x11_capture_end_to_end() {
|
||||
let Some(display) = std::env::var("DISPLAY").ok().filter(|d| !d.is_empty()) else {
|
||||
eprintln!("skipped: DISPLAY is not set");
|
||||
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
|
||||
else {
|
||||
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
|
||||
return;
|
||||
};
|
||||
let scene = Scene::create(&display);
|
||||
|
||||
@@ -282,7 +282,7 @@ impl Peer {
|
||||
) -> Result<(Self, String), PeerError> {
|
||||
let start = options.start_bitrate.unwrap_or(DEFAULT_START_BITRATE).max(1);
|
||||
let bwe = config.bandwidth_estimation.then_some(start);
|
||||
let (mut rtc, srtp_profile) = build_rtc(config, &config.video_codecs, bwe);
|
||||
let (mut rtc, srtp_profile) = build_rtc(config, &config.video_codecs, true, bwe);
|
||||
if bwe.is_some() {
|
||||
let desired = options.desired_bitrate.unwrap_or(start);
|
||||
rtc.bwe().set_desired_bitrate(Bitrate::bps(desired));
|
||||
@@ -333,7 +333,7 @@ impl Peer {
|
||||
}
|
||||
}
|
||||
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
|
||||
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, None);
|
||||
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, false, None);
|
||||
let net = Net::bind(config, &mut rtc).await?;
|
||||
let answer = rtc.sdp_api().accept_offer(offer)?;
|
||||
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
|
||||
@@ -462,10 +462,15 @@ fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
|
||||
}
|
||||
|
||||
/// An RTC with Opus and `video` codecs, in this order of preference, our
|
||||
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given.
|
||||
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given. An
|
||||
/// offer lists H.264 only as our encoders produce it (`profile-level-id`
|
||||
/// [`PeerConfig::h264_profile_level_id`], packetization mode 1): with
|
||||
/// str0m's other variants offered too, a viewer may answer a profile we
|
||||
/// never send. An answer takes every variant the offer has.
|
||||
fn build_rtc(
|
||||
config: &PeerConfig,
|
||||
video: &[VideoCodec],
|
||||
offer: bool,
|
||||
bwe: Option<u64>,
|
||||
) -> (Rtc, NegotiatedProfile) {
|
||||
let mut rtc_config =
|
||||
@@ -475,7 +480,7 @@ fn build_rtc(
|
||||
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
|
||||
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
|
||||
VideoCodec::H264 => {
|
||||
let mut c = rtc_config.enable_h264(true);
|
||||
let mut c = if offer { rtc_config } else { rtc_config.enable_h264(true) };
|
||||
c.codec_config().add_h264(
|
||||
112.into(),
|
||||
Some(113.into()),
|
||||
@@ -935,6 +940,9 @@ mod tests {
|
||||
};
|
||||
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
|
||||
// Only the profile we encode: a viewer must not answer another.
|
||||
let h264 = offer.lines().filter(|l| l.contains(" H264/90000")).count();
|
||||
assert_eq!(h264, 1, "{offer}");
|
||||
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
|
||||
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
|
||||
let vp8_only =
|
||||
|
||||
@@ -4,82 +4,23 @@
|
||||
//!
|
||||
//! Runs only with `VOELIN_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 serde_json::json;
|
||||
use tokio::time::timeout;
|
||||
use voelin_stream::{
|
||||
Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile,
|
||||
SyntheticSource,
|
||||
};
|
||||
|
||||
fn enabled() -> bool {
|
||||
std::env::var("VOELIN_INTEROP").is_ok_and(|v| v == "1")
|
||||
}
|
||||
#[path = "../../../tests/interop/browser.rs"]
|
||||
mod browser;
|
||||
use browser::{Browser, enabled};
|
||||
|
||||
/// 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("VOELIN_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 VOELIN_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;
|
||||
}
|
||||
/// The `srtpCipher` of `getStats()` for AES_CM_128_HMAC_SHA1_80, as Chromium
|
||||
/// 141 and 152 name it.
|
||||
fn aes_cm_128_sha1_80(cipher: &serde_json::Value) -> bool {
|
||||
["AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_HMAC_SHA1_80"].iter().any(|name| cipher == name)
|
||||
}
|
||||
|
||||
async fn wait_connected(peer: &mut Peer) {
|
||||
@@ -139,7 +80,7 @@ async fn rust_streams_to_browser() {
|
||||
eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}");
|
||||
eprintln!("bandwidth estimates (bit/s): {estimates:?}");
|
||||
assert_eq!(stats["connectionState"], "connected");
|
||||
assert_eq!(stats["transport"]["srtpCipher"], "AES_CM_128_HMAC_SHA1_80", "{stats:#}");
|
||||
assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}");
|
||||
assert_eq!(peer.srtp_profile(), Some(SrtpProfile::Aes128CmSha1_80));
|
||||
assert!(!estimates.is_empty(), "no bandwidth estimate from the browser's feedback");
|
||||
let video = &stats["inbound"]["video"];
|
||||
@@ -329,6 +270,6 @@ async fn browser_streams_to_rust() {
|
||||
}
|
||||
assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}");
|
||||
let stats = browser.call(json!({ "op": "stats" })).await;
|
||||
assert_eq!(stats["transport"]["srtpCipher"], "AES_CM_128_HMAC_SHA1_80", "{stats:#}");
|
||||
assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}");
|
||||
browser.quit().await;
|
||||
}
|
||||
+16
-8
@@ -160,18 +160,26 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
- `peer_config(&codecs, config)` makes a viewer accept only what we decode
|
||||
and a streamer offer its stream codec (the first of `config.video_codecs`
|
||||
it can encode) followed by `offer_codecs`: the codecs of hardware
|
||||
encoders, VP8 through libvpx (every TeamSpeak client decodes it), and HEVC
|
||||
encoders and VP8 through libvpx that every TeamSpeak client decodes
|
||||
(`decoded_everywhere`: AV1, VP9, VP8), then H.264 from hardware, and HEVC
|
||||
last. Other software encoders (x264, SVT-AV1, libvpx VP9, ...) are only
|
||||
ever the stream codec, so a viewer's answer never starts an expensive
|
||||
second encoder. Answers keep the offer's order, so viewers take the stream
|
||||
codec when they decode it. `preferred_codec(&codecs, configured)` picks the
|
||||
stream codec: `stream.codec` if encodable, else the preference's first
|
||||
(hardware first when enabled, VP8 in software; never HEVC);
|
||||
`encoder_preference(&settings)` and `configured_codec(&settings)` read the
|
||||
settings. H.264 is offered as Constrained High at the level the stream
|
||||
needs (`PeerConfig::set_h264_format(profile, width, height, fps, bitrate)`:
|
||||
codec every TeamSpeak client decodes (hardware first when enabled, VP8 in
|
||||
software), else any but HEVC; `encoder_preference(&settings)` and
|
||||
`configured_codec(&settings)` read the settings. The official client
|
||||
decodes H.264 only with an OpenH264 library it downloads at start-up; when
|
||||
that fails it still answers H.264 and shows nothing (see
|
||||
`docs/protocol-notes/ts6-streaming.md`), so H.264 never comes before a
|
||||
codec it always decodes. H.264 is offered as one variant, Constrained High
|
||||
(packetization mode 1) at the level the stream needs
|
||||
(`PeerConfig::set_h264_format(profile, width, height, fps, bitrate)`:
|
||||
macroblocks per second and per frame, and bitrate, per H.264 Table A-1;
|
||||
never below 3.1, the level offered before).
|
||||
never below 3.1, the level offered before); str0m's other H.264 variants
|
||||
are only accepted, never offered, so a viewer cannot answer a profile we
|
||||
do not send.
|
||||
- `VideoPipeline` decodes on its own thread. It starts at a keyframe, and
|
||||
after a lost frame (`contiguous == false`, a lagging frame bus, a queue
|
||||
longer than 30 frames) or a decoder error it skips to the next keyframe,
|
||||
@@ -968,7 +976,7 @@ has not run on Windows yet.
|
||||
| OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) |
|
||||
| H.264 library missing / unknown file | unit + integration tests | tested |
|
||||
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; streams of SVT-AV1, rav1e, libaom, `av1_vaapi` and `av1_amf` decoded (rows below) |
|
||||
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb | tested |
|
||||
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested |
|
||||
| wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) |
|
||||
| Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested |
|
||||
| Simulcast layers (sizes, fps caps, per-layer keyframes), reconfigure (codec, layers, fps) | `voelin-core` `media::tests::simulcast_layers_and_reconfigure` | tested |
|
||||
@@ -1008,7 +1016,7 @@ has not run on Windows yet.
|
||||
| Stream mixer (latency, fade on underrun, drift correction, rate conversion, limiter, levels, live source changes), `BlockClock` | `voelin-media` `mix::tests`, `tests/mix_alloc.rs` (no allocation per block) | tested |
|
||||
| Application audio on PipeWire: desktop without our own stream, by name, by pid, a new player linked live, a quit one dropped, a restarted one matched again, the app list | `voelin-media/tests/pipewire_apps.rs` (private PipeWire, WirePlumber and D-Bus; tones told apart by frequency) | tested with PipeWire 1.0 and WirePlumber 0.4; skipped without them |
|
||||
| Streamer audio sources (mix levels, gain, mute, live change, microphone tap, window source error, silence) | `voelin-core` `media::tests::audio_sources_change_live`, `audio_sources_from_settings`, `settings::tests::audio_sources` | tested |
|
||||
| X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb | tested |
|
||||
| X11 `_NET_WM_PID` of the shared window | `tests/x11_capture.rs` under Xvfb (`VOELIN_X11_TEST_DISPLAY`) | tested |
|
||||
| WASAPI per-process loopback, audio sessions, `HWND` owner | – | type-checked for `x86_64-pc-windows-gnu` only |
|
||||
| Android per-app and all-but-ours playback capture | `cargo ndk -t arm64-v8a clippy`, `gradlew compileDebugKotlin` | compiles only (no device or emulator here) |
|
||||
| The same through the TeamSpeak 6 server | `voelin-core/tests/media_live.rs` (`VOELIN_LIVE=1`), `voelinctl stream start --synthetic` / `watch --expect-frames` | tested against 6.0.0-beta13.1 |
|
||||
|
||||
@@ -38,7 +38,8 @@ Transport (**reported**, TeamSpeak staff on community.teamspeak.com):
|
||||
Codecs (**reported**, from the ts6-manager bot's working code):
|
||||
|
||||
- Video: H.264 Constrained High (the only H.264 profile the TS client decodes),
|
||||
VP8, VP9, AV1.
|
||||
VP8, VP9, AV1. H.264 only when the client could download OpenH264 (see
|
||||
"Codecs the official client decodes" below).
|
||||
- Audio: Opus, 48 kHz stereo, payload type 111.
|
||||
|
||||
Commands over the normal client command channel (**reported**, ts6-manager,
|
||||
@@ -253,6 +254,36 @@ libwebrtc, the stack the official client is built on:
|
||||
feedback gives estimates; the offer is the same as without (str0m always
|
||||
offers transport-cc and abs-send-time).
|
||||
|
||||
### Codecs the official client decodes (confirmed, client 6.0.0-beta4.1, 2026-10-03)
|
||||
|
||||
From the official Linux client's log (`~/.cache/TeamSpeak/Default/logs/`)
|
||||
while it watched a Voelin stream, and the symbols of its binary:
|
||||
|
||||
- At start-up it downloads Cisco's OpenH264
|
||||
(`http://ciscobinary.openh264.org/libopenh264-2.6.0-linux64.8.so.bz2`); here
|
||||
the download failed (`Failed to download openh264 binary http code: 403`).
|
||||
- Voelin offered H.264 first (the hardware encoder's codec), with every H.264
|
||||
variant str0m knows. The client answered H.264 `profile-level-id=42e01f`
|
||||
(packetization mode 1), then could not make a decoder for it: `Trying to
|
||||
create decoder for unsupported format. Codec name: H264` — libwebrtc's
|
||||
`NullVideoDecoder`, nothing shown. Its SDP capabilities list H.264 whether
|
||||
or not OpenH264 loaded.
|
||||
- Its decoders: `FFmpegDecoderVP8`, `FFmpegDecoderVP9`, `FFmpegDecoderAV1`
|
||||
(FFmpeg bundled in `/opt/teamspeak`, dav1d and libaom linked in), AMF
|
||||
hardware decoders for H.264 and AV1, and OpenH264 (`H264DecoderImpl`) once
|
||||
downloaded. VP8, VP9 and AV1 therefore always decode; H.264 depends on the
|
||||
download.
|
||||
- It answers with the first codec of the offer it lists, like Chromium.
|
||||
|
||||
Voelin now offers codecs every client decodes first (`decoded_everywhere`)
|
||||
and H.264 only in the profile it encodes. The real encoders' streams (VA-API
|
||||
H.264 and AV1, from memory and from DMA-BUFs; libvpx VP8 and VP9; x264,
|
||||
SVT-AV1, libaom) decode in Chromium 152's libwebrtc at full size
|
||||
(`crates/voelin-core/tests/browser_codecs.rs`). Watching such a stream with
|
||||
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.
|
||||
|
||||
## Open questions
|
||||
|
||||
- [x] Viewer side: `joinstreamrequest id clid msg is_remove` (see above).
|
||||
@@ -264,9 +295,9 @@ libwebrtc, the stack the official client is built on:
|
||||
- [x] Whether a client that connects later is told about running streams: no (see above).
|
||||
- [x] How a client finds running streams after connecting: `requeststreaminfo`
|
||||
(presumably what the official client does too; not captured from it).
|
||||
- [ ] Interop with the official TS6 client (its offer/answer details, codecs it
|
||||
actually picks, whether it trickles candidates, mDNS host candidates).
|
||||
Chromium's WebRTC stack interoperates (see above).
|
||||
- [ ] Interop with the official TS6 client (its offer/answer details, whether
|
||||
it trickles candidates, mDNS host candidates). The codecs it picks and
|
||||
decodes are known (see above); Chromium's WebRTC stack interoperates.
|
||||
- [ ] Whether stream audio can be sent without video.
|
||||
- [ ] The WebRTC/protobuf transport some TS6 clients use on UDP 9987
|
||||
(`client_protocol_format=proto`, reported in community reverse engineering).
|
||||
|
||||
+26
-4
@@ -1,15 +1,19 @@
|
||||
# Browser interop test
|
||||
|
||||
`crates/voelin-stream/tests/browser_interop.rs` checks our str0m peers against
|
||||
the WebRTC stack of Chromium (libwebrtc, the same stack as the official
|
||||
`crates/voelin-stream/tests/browser_interop.rs` checks our str0m peers, and
|
||||
`crates/voelin-core/tests/browser_codecs.rs` our real encoders, 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.
|
||||
Playwright and exchanges SDP and candidates with the Rust tests as JSON lines
|
||||
on stdin/stdout (`browser.rs` is the Rust side, shared by both tests). 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; the `transport` stats' `srtpCipher` is `AES_CM_128_HMAC_SHA1_80` (our SRTP order, we are the DTLS server); our bandwidth estimation gets estimates from Chromium's transport-cc feedback |
|
||||
| `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 |
|
||||
| `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
|
||||
@@ -20,8 +24,16 @@ elsewhere).
|
||||
|
||||
```sh
|
||||
VOELIN_INTEROP=1 cargo test -p voelin-stream --test browser_interop -- --nocapture
|
||||
VOELIN_INTEROP=1 cargo test -p voelin-core --features media-desktop --test browser_codecs -- --nocapture
|
||||
```
|
||||
|
||||
Without Playwright's own browsers, `playwright-core` drives an installed
|
||||
Chromium: `npm install playwright-core` somewhere, then
|
||||
`NODE_PATH=<that>/node_modules VOELIN_CHROMIUM=/usr/bin/chromium`. A system
|
||||
Chromium usually decodes H.264, which Playwright's build does not. Run it
|
||||
headless and away from the desktop session, e.g. with `WAYLAND_DISPLAY` and
|
||||
`DISPLAY` unset under `dbus-run-session`.
|
||||
|
||||
Without `VOELIN_INTEROP=1` the tests return immediately, so `cargo test` passes on
|
||||
machines without a browser. `VOELIN_NODE` selects the node binary; `NODE_PATH`
|
||||
defaults to `npm root -g` so a global Playwright is found.
|
||||
@@ -49,6 +61,16 @@ may do the same; see `docs/protocol-notes/ts6-streaming.md`.
|
||||
(`PeerConfig::srtp_profiles`) the connection uses AES_CM_128_HMAC_SHA1_80
|
||||
(`getStats()` transport: `srtpCipher`, DTLS 1.2 `FEFD`,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`). Before, dimpl picked AES-256-GCM.
|
||||
Chromium 152 names the same cipher `SRTP_AES128_CM_HMAC_SHA1_80`.
|
||||
- Chromium 152 (Arch Linux build) decodes every encoder's stream on this
|
||||
machine (AMD, VA-API): H.264 and AV1 from VA-API (from memory and from
|
||||
DMA-BUFs), VP8 and VP9 from libvpx, x264, SVT-AV1 and libaom, all at
|
||||
1280x720, about 100 frames in 3.4 s, no freezes.
|
||||
- Headless Chromium 152 lists H.264 only in the profiles of libwebrtc's
|
||||
software decoder (Baseline, Constrained Baseline, Main, packetization modes
|
||||
0 and 1): it does not answer an offer of Constrained High alone
|
||||
(`640c1f`, what our streamers offer), yet decodes High profile streams
|
||||
when it negotiated another profile (its decoder is FFmpeg's).
|
||||
- With str0m's bandwidth estimation and pacer on our streamer peer, Chromium's
|
||||
transport-cc feedback yields estimates within the first second (about
|
||||
640 kbit/s rising towards the desired bitrate with the 720 kbit/s synthetic
|
||||
|
||||
@@ -10,14 +10,22 @@
|
||||
// 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,
|
||||
// stats connection state, inbound/outbound RTP counters
|
||||
// (incl. the decoder and decoded frame size),
|
||||
// frames shown by a <video> element, the DTLS/SRTP
|
||||
// parameters of the transport
|
||||
// quit
|
||||
'use strict';
|
||||
|
||||
const readline = require('node:readline');
|
||||
const { chromium } = require('playwright');
|
||||
// Playwright, or playwright-core driving a browser it did not download
|
||||
// (`VOELIN_CHROMIUM`, e.g. a system Chromium that decodes H.264).
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = require('playwright'));
|
||||
} catch {
|
||||
({ chromium } = require('playwright-core'));
|
||||
}
|
||||
|
||||
// Runs in the page.
|
||||
const PAGE_SCRIPT = `
|
||||
@@ -151,7 +159,7 @@ window.peer = {
|
||||
out.transport = {};
|
||||
['dtlsState', 'dtlsRole', 'tlsVersion', 'dtlsCipher', 'srtpCipher'].forEach((k) => (out.transport[k] = transport[k]));
|
||||
for (const k in inbound) {
|
||||
out.inbound[k] = pick(inbound[k], ['packetsReceived', 'bytesReceived', 'packetsLost', 'framesReceived', 'framesDecoded', 'keyFramesDecoded', 'pliCount', 'totalSamplesReceived']);
|
||||
out.inbound[k] = pick(inbound[k], ['packetsReceived', 'bytesReceived', 'packetsLost', 'framesReceived', 'framesDecoded', 'keyFramesDecoded', 'framesDropped', 'frameWidth', 'frameHeight', 'decoderImplementation', 'freezeCount', 'pliCount', 'totalSamplesReceived']);
|
||||
}
|
||||
for (const k in outbound) {
|
||||
out.outbound[k] = pick(outbound[k], ['packetsSent', 'bytesSent', 'framesEncoded', 'keyFramesEncoded', 'pliCount']);
|
||||
@@ -169,6 +177,7 @@ window.peer = {
|
||||
async function main() {
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath: process.env.VOELIN_CHROMIUM || undefined,
|
||||
args: [
|
||||
// Real host candidates instead of mDNS names (no getUserMedia permission here).
|
||||
'--disable-features=WebRtcHideLocalIpsWithMdns',
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! The Node.js side of the browser interop tests (headless Chromium through
|
||||
//! `tests/interop/browser-peer.cjs`), shared by the tests of several crates
|
||||
//! with `#[path = ".../tests/interop/browser.rs"] mod browser;`.
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
|
||||
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
|
||||
use tokio::time::timeout;
|
||||
|
||||
/// The tests run only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`).
|
||||
pub fn enabled() -> bool {
|
||||
std::env::var("VOELIN_INTEROP").is_ok_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// Headless Chromium, driven over stdin/stdout.
|
||||
pub struct Browser {
|
||||
_child: Child,
|
||||
stdin: ChildStdin,
|
||||
stdout: Lines<BufReader<ChildStdout>>,
|
||||
}
|
||||
|
||||
impl Browser {
|
||||
pub async fn start() -> Self {
|
||||
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/interop/browser-peer.cjs")
|
||||
.canonicalize()
|
||||
.expect("tests/interop/browser-peer.cjs");
|
||||
let node = std::env::var("VOELIN_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 VOELIN_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
|
||||
}
|
||||
|
||||
pub 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
|
||||
}
|
||||
|
||||
pub async fn quit(mut self) {
|
||||
let _ = self.call(json!({ "op": "quit" })).await;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user