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();
|
||||
}
|
||||
Reference in new issue
Block a user