Merge branch 'claude/gifted-lovelace-1crlx2' into worktree-agent-a33c34a3879196dbf
This commit is contained in:
commit
2159b38786
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;
|
||||
}
|
||||
Reference in new issue
Block a user