use std::sync::{Arc, Mutex};
use super::tests::{connect_test, fake_airplay, SharedTally, Tallied};
use super::*;
use crate::airplay::fake_mirror::{Behaviour, FakeMirror};
use crate::airplay::MirrorOptions;
use crate::cast::fake_receiver::{FakeReceiver, Options as CastFake};
use crate::codec::json::Value;
use crate::net::http::{Conn, Request, Version};
type Report = Arc<Mutex<Vec<String>>>;
fn env(name: &str) -> Option<String> {
std::env::var(format!("TVPIPE_TEST_BROWSER_{name}")).ok()
}
fn secs() -> u64 {
env("SECS").and_then(|s| s.parse().ok()).unwrap_or(6)
}
static SERIAL: Mutex<()> = Mutex::new(());
static STOP: std::sync::LazyLock<crate::util::stop::Stop> =
std::sync::LazyLock::new(crate::util::stop::Stop::new);
fn share_in_browser(drive: impl FnOnce(String, Report) + Send + 'static) {
let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
STOP.clear();
if env("DEBUG").is_some() {
crate::log::set_level(crate::log::Level::Debug);
}
let rx = FakeReceiver::spawn(CastFake::default());
let fake = FakeMirror::start(Behaviour {
nack_after: None,
..Behaviour::default()
});
let (cast_tally, airplay_tally) = (SharedTally::default(), SharedTally::default());
let connect = |t: &Target, c: &CastOptions, m: &MirrorOptions| -> Result<Box<dyn Sink>> {
Ok(match t {
Target::Browser(_) => connect_test(t, c, m)?,
Target::Cast { addr, name } => {
Tallied::boxed(Box::new(cast::connect(*addr, name, c)?), None, &cast_tally)
}
Target::AirPlay { .. } => {
let m = MirrorOptions {
ptp: false,
..m.clone()
};
Tallied::boxed(
fake_airplay(&fake, "fake-airplay", &m)?,
None,
&airplay_tally,
)
}
})
};
let report: Report = Arc::default();
let driver = Mutex::new(None);
let drive = Mutex::new(Some(drive));
let hook = |server: &ShareServer| {
let url = server.url().to_owned();
let report = report.clone();
let drive = drive.lock().unwrap().take().unwrap();
*driver.lock().unwrap() = Some(std::thread::spawn(move || {
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drive(url, report)));
STOP.request();
r
}));
};
let real = env("TO");
let to = match &real {
Some(addr) => vec![addr.clone()],
None => vec![rx.addr.to_string(), format!("airplay:{}", fake.addr)],
};
let o = ShareOptions {
to,
latency_ms: None,
size: env("SIZE").map(|s| s.parse().unwrap()),
fps: None,
bitrate_kbps: None,
no_audio: false,
open: false,
..ShareOptions::default()
};
let r = if real.is_some() {
share_with(o, &connect_test, &Ctx::from(STOP.clone()), &hook)
} else {
share_with(o, &connect, &Ctx::from(STOP.clone()), &hook)
};
let drove = driver.lock().unwrap().take().map(|h| h.join());
for line in report.lock().unwrap().iter() {
eprintln!("page: {line}");
}
if let Some(Ok(Err(panic))) = drove {
std::panic::resume_unwind(panic);
}
r.unwrap();
if real.is_some() {
return;
}
let state = rx.shutdown();
let st = state.lock().unwrap();
let (tc, ta) = (*cast_tally.lock().unwrap(), *airplay_tally.lock().unwrap());
eprintln!("cast {tc:?}\nairplay {ta:?}");
let v = st.streams.iter().find(|s| s.codec == "h264").unwrap();
for s in &st.streams {
eprintln!("cast stream {}: {} frames", s.codec, s.frames.len());
}
if let Some(path) = env("DUMP") {
let all: Vec<u8> = v.frames.values().flat_map(|f| f.data.clone()).collect();
std::fs::write(&path, all).unwrap();
if let Some(a) = st.streams.iter().find(|s| s.codec == "aac") {
let adts: Vec<u8> = a.frames.values().flat_map(|f| f.data.clone()).collect();
std::fs::write(format!("{path}.aac"), adts).unwrap();
}
eprintln!("wrote {path}");
}
assert!(tc.video > secs() * 10, "{tc:?}");
assert!(ta.audio > 0 && tc.audio > 0, "{tc:?} {ta:?}");
}
fn check_place(eval: &mut dyn FnMut(&str) -> Value) {
for (sw, sh, dw, dh) in [
(1920u32, 1200u32, 1920u32, 1080u32),
(800, 600, 1066, 600),
(1920, 800, 1440, 1080),
(333, 777, 1920, 1080),
(1919, 1201, 1280, 720),
(1, 99999, 2, 2),
] {
let js = eval(&format!(
"return JSON.stringify(tvpipeCapture.place({sw}, {sh}, {dw}, {dh}))"
));
let r = crate::browser::layout::place((sw, sh), (dw, dh));
let rust = format!(
r#"{{"x":{},"y":{},"width":{},"height":{}}}"#,
r.x, r.y, r.width, r.height
);
assert_eq!(js.as_str(), Some(rust.as_str()), "{sw}x{sh} in {dw}x{dh}");
}
}
fn watch(eval: &mut dyn FnMut(&str) -> Value, report: &Report) {
let t0 = Instant::now();
let total = Duration::from_secs(secs());
let mut asked = false;
while t0.elapsed() < total {
std::thread::sleep(Duration::from_millis(1000));
if !asked && t0.elapsed() >= total / 2 {
asked = true;
eval("tvpipeShare._message({type: 'keyframe'}); return 1");
}
let s = eval(
"return JSON.stringify({stats: window.tvpipeLastStats || null, \
log: [...document.getElementById('log').children].map(e => e.textContent).join('\\n'), \
capture: document.getElementById('capture').textContent, \
plan: document.getElementById('plan').textContent})",
);
report
.lock()
.unwrap()
.push(s.as_str().unwrap_or("?").to_owned());
}
std::thread::sleep(Duration::from_millis(2200));
let s = eval("return JSON.stringify(window.tvpipeKeyLatency === undefined ? null : window.tvpipeKeyLatency)");
report
.lock()
.unwrap()
.push(format!("keyframe request answered in {s} ms"));
assert!(
s.as_str().is_some_and(|v| v != "null"),
"the keyframe request was not answered"
);
}
pub(super) struct Chrome {
browser: crate::browser::launch::Browser,
session: String,
_profile: crate::browser::launch::Profile,
}
impl Chrome {
pub(super) fn call(&mut self, method: &str, params: Value) -> Value {
self.browser
.cdp()
.call(Some(&self.session), method, params)
.unwrap_or_else(|e| panic!("{method}: {e}"))
}
pub(super) fn eval(&mut self, body: &str) -> Value {
self.browser
.cdp()
.evaluate(
&self.session,
&format!("(async () => {{ {body} }})()"),
true,
true,
Duration::from_secs(30),
)
.unwrap_or_else(|e| {
eprintln!("eval {body}: {e}");
Value::Null
})
}
pub(super) fn profile_dir(&self) -> std::path::PathBuf {
self._profile.dir().to_path_buf()
}
}
fn viewport() -> (u32, u32) {
let v: Size = std::env::var("TVPIPE_TEST_CHROME_VIEWPORT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(Size {
width: 1920,
height: 1080,
});
(v.width, v.height)
}
pub(super) fn chrome(bin: &str, url: &str) -> Chrome {
let profile = crate::browser::launch::Profile::temporary().unwrap();
let opts = crate::browser::launch::LaunchOptions {
bin: bin.into(),
viewport: viewport(),
visible: std::env::var("TVPIPE_TEST_CHROME_HEADED").is_ok(),
screen: None,
};
let browser = crate::browser::launch::Browser::launch(&opts, &profile).unwrap();
let (_, session) = crate::browser::headless::attach(&browser, opts.viewport).unwrap();
let mut c = Chrome {
browser,
session,
_profile: profile,
};
let r = c.call("Page.navigate", Value::object().with("url", url));
assert!(r.get("errorText").is_none(), "{url}: {r}");
c
}
#[test]
#[ignore]
fn chrome_share_to_fakes() {
let Ok(bin) = std::env::var("TVPIPE_TEST_CHROME") else {
eprintln!("TVPIPE_TEST_CHROME not set");
return;
};
share_in_browser(move |url, report| {
let mut chrome = chrome(&bin, &url);
let mut eval = |s: &str| chrome.eval(s);
let deadline = Instant::now() + Duration::from_secs(20);
while eval("return !!(window.tvpipeShare && window.tvpipeShare.config)")
!= Value::Bool(true)
{
assert!(Instant::now() < deadline, "the page got no config");
std::thread::sleep(Duration::from_millis(100));
}
let geo = eval(
"return JSON.stringify([innerWidth, innerHeight, outerWidth, outerHeight, \
devicePixelRatio, screen.width, screen.height])",
);
report.lock().unwrap().push(format!("geometry: {geo}"));
let (vw, vh) = viewport();
let g = geo.as_str().unwrap_or("");
assert!(
g.starts_with(&format!("[{vw},{vh},")),
"viewport is not {vw}x{vh}: {geo}"
);
assert!(g.contains(",1,"), "scale: {geo}");
check_place(&mut eval);
eval(
"const c = document.createElement('canvas'); c.width = 640; c.height = 200; \
document.body.prepend(c); const g = c.getContext('2d'); let n = 0; \
(function draw() { g.fillStyle = `hsl(${n % 360},80%,50%)`; g.fillRect(0, 0, 640, 200); \
g.fillStyle = '#fff'; g.font = '48px sans-serif'; g.fillText(String(n++), 20, 120); \
requestAnimationFrame(draw); })(); \
const a = new AudioContext(); const o = a.createOscillator(); o.frequency.value = 440; \
o.connect(a.destination); o.start(); return a.state;",
);
if std::env::var("TVPIPE_TEST_CHROME_NO_MSTP").is_ok() {
eval("window.MediaStreamTrackProcessor = undefined; tvpipeShare.opts.worker = false; return 1");
}
let r = eval(
"tvpipeShare.opts.preferCurrentTab = true; tvpipeShare.opts.selfBrowserSurface = 'include'; \
return tvpipeShare.captureDisplay().then(() => 'ok', e => 'error: ' + e.name + ': ' + e.message)",
);
report.lock().unwrap().push(format!("captureDisplay: {r}"));
watch(&mut eval, &report);
drop(chrome);
});
}
pub(super) struct Firefox {
browser: crate::browser::launch::Browser,
context: String,
profile: crate::browser::launch::Profile,
}
impl Firefox {
pub(super) fn eval(&mut self, body: &str) -> Value {
crate::browser::bidi::evaluate(
self.browser.cdp(),
&self.context,
&format!("(async () => {{ {body} }})()"),
true,
true,
Duration::from_secs(30),
)
.unwrap_or_else(|e| {
eprintln!("eval {body}: {e}");
Value::Null
})
}
pub(super) fn profile_dir(&self) -> std::path::PathBuf {
self.profile.dir().to_path_buf()
}
pub(super) fn open_tab_in_front(&self, url: &str) {
let r = self
.browser
.cdp()
.call(
None,
"browsingContext.create",
Value::object()
.with("type", "tab")
.with("background", false),
)
.unwrap();
let ctx = r.get("context").and_then(Value::as_str).unwrap();
crate::browser::headless::firefox::navigate(self.browser.cdp(), ctx, url).unwrap();
}
}
pub(super) fn firefox_bin() -> Option<String> {
std::env::var("TVPIPE_TEST_FIREFOX").ok()
}
pub(super) fn firefox(bin: &str, url: &str, viewport: (u32, u32)) -> Firefox {
let profile = crate::browser::launch::Profile::temporary().unwrap();
let opts = crate::browser::launch::LaunchOptions {
bin: bin.into(),
viewport,
visible: std::env::var("TVPIPE_TEST_FIREFOX_HEADED").is_ok(),
screen: None,
};
assert_eq!(
opts.engine(),
crate::browser::launch::Engine::Firefox,
"{bin} is not Firefox"
);
let browser = crate::browser::launch::Browser::launch(&opts, &profile).unwrap();
let context = crate::browser::headless::firefox::attach(&browser, viewport).unwrap();
crate::browser::headless::firefox::navigate(browser.cdp(), &context, url).unwrap();
Firefox {
browser,
context,
profile,
}
}
#[test]
#[ignore]
fn firefox_share_to_fakes() {
let Some(bin) = firefox_bin() else {
eprintln!("TVPIPE_TEST_FIREFOX not set");
return;
};
share_in_browser(move |url, report| {
let mut ff = firefox(&bin, &url, (1280, 800));
let mut eval = |s: &str| ff.eval(s);
let deadline = Instant::now() + Duration::from_secs(20);
while eval("return !!(window.tvpipeShare && window.tvpipeShare.config)")
!= Value::Bool(true)
{
assert!(Instant::now() < deadline, "the page got no config");
std::thread::sleep(Duration::from_millis(100));
}
let f = eval("return JSON.stringify(tvpipeCapture.features())");
report.lock().unwrap().push(format!("features: {f}"));
let howto = eval("return document.getElementById('howto').hidden ? '' : document.getElementById('howto').innerText");
report
.lock()
.unwrap()
.push(format!("how-to shown: {howto}"));
assert!(
howto.as_str().is_some_and(|h| h.contains("Firefox")),
"Firefox's how-to is missing: {howto}"
);
check_place(&mut eval);
eval(
"const c = document.createElement('canvas'); c.width = 640; c.height = 200; \
document.body.prepend(c); const g = c.getContext('2d'); let n = 0; \
(function draw() { g.fillStyle = `hsl(${n % 360},80%,50%)`; g.fillRect(0, 0, 640, 200); \
g.fillStyle = '#fff'; g.font = '48px sans-serif'; g.fillText(String(n++), 20, 120); \
requestAnimationFrame(draw); })(); \
const a = new AudioContext(); const o = a.createOscillator(); o.frequency.value = 440; \
o.connect(a.destination); o.start(); return a.state;",
);
let screen = std::env::var("TVPIPE_TEST_FIREFOX_SCREEN").is_ok();
let r = eval(&format!(
"tvpipeShare.opts.preferCurrentTab = {}; \
return tvpipeShare.captureDisplay().then(() => 'ok', e => 'error: ' + e.name + ': ' + e.message)",
!screen
));
report.lock().unwrap().push(format!("captureDisplay: {r}"));
assert_eq!(r.as_str(), Some("ok"), "{r}");
watch(&mut eval, &report);
let mode = eval("return window.tvpipeLastStats && window.tvpipeLastStats.mode");
report.lock().unwrap().push(format!("engine: {mode}"));
ff.open_tab_in_front("about:blank");
std::thread::sleep(Duration::from_secs(5));
let s =
ff.eval("return JSON.stringify([document.visibilityState, window.tvpipeLastStats])");
report
.lock()
.unwrap()
.push(format!("in the background: {s}"));
let v = Value::parse(s.as_str().unwrap_or("null")).unwrap_or(Value::Null);
assert_eq!(v.at(0).and_then(Value::as_str), Some("hidden"), "{s}");
let fps = v
.at(1)
.and_then(|st| st.get("fps"))
.and_then(Value::as_f64)
.unwrap_or(0.0);
assert!(fps >= 20.0, "{fps} fps in the background: {s}");
drop(ff);
});
}
pub(super) struct WebDriver {
port: u16,
session: String,
child: std::process::Child,
}
pub(super) fn webdriver_call(port: u16, method: &str, path: &str, body: Option<&Value>) -> Value {
let tcp = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(60))).unwrap();
let mut c = Conn::new(tcp);
let mut req = Request::new(method, path, Version::Http11)
.header("Host", format!("127.0.0.1:{port}"))
.header("Connection", "close");
if let Some(b) = body {
req = req.body("application/json", b.to_json().into_bytes());
}
let resp = c.request(&req).unwrap();
let v = Value::parse(std::str::from_utf8(&resp.body).unwrap()).unwrap();
v.get("value").cloned().unwrap_or(Value::Null)
}
impl WebDriver {
pub(super) fn start() -> WebDriver {
let port = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let child = std::process::Command::new("safaridriver")
.args(["-p", &port.to_string()])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("safaridriver");
let deadline = Instant::now() + Duration::from_secs(10);
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(Instant::now() < deadline, "safaridriver did not start");
std::thread::sleep(Duration::from_millis(50));
}
let caps = Value::object().with(
"capabilities",
Value::object().with(
"alwaysMatch",
Value::object()
.with("browserName", "safari")
.with("webkit:alwaysAllowAutoplay", true),
),
);
let v = webdriver_call(port, "POST", "/session", Some(&caps));
let session = v
.get("sessionId")
.and_then(Value::as_str)
.unwrap_or_else(|| {
panic!("no WebDriver session (Develop > Allow Remote Automation?): {v}")
})
.to_owned();
WebDriver {
port,
session,
child,
}
}
pub(super) fn call(&self, method: &str, path: &str, body: Option<&Value>) -> Value {
webdriver_call(
self.port,
method,
&format!("/session/{}{path}", self.session),
body,
)
}
pub(super) fn eval(&self, body: &str) -> Value {
let script = format!(
"const done = arguments[arguments.length - 1]; \
(async () => {{ {body} }})().then(done, e => done('error: ' + e));"
);
let b = Value::object()
.with("script", script)
.with("args", Value::array(Vec::<Value>::new()));
self.call("POST", "/execute/async", Some(&b))
}
}
impl Drop for WebDriver {
fn drop(&mut self) {
webdriver_call(
self.port,
"DELETE",
&format!("/session/{}", self.session),
None,
);
let _ = self.child.kill();
let _ = self.child.wait();
}
}
#[test]
#[ignore]
fn safari_share_to_fakes() {
if std::env::var("TVPIPE_TEST_SAFARI").is_err() {
eprintln!("TVPIPE_TEST_SAFARI not set");
return;
}
share_in_browser(move |url, report| {
let wd = WebDriver::start();
wd.call(
"POST",
"/url",
Some(&Value::object().with("url", url.as_str())),
);
let mut eval = |s: &str| wd.eval(s);
let deadline = Instant::now() + Duration::from_secs(20);
while eval("return !!(window.tvpipeShare && window.tvpipeShare.config)")
!= Value::Bool(true)
{
assert!(Instant::now() < deadline, "the page got no config");
std::thread::sleep(Duration::from_millis(100));
}
let f = eval("return JSON.stringify(tvpipeCapture.features())");
report.lock().unwrap().push(format!("features: {f}"));
let howto = eval("return document.getElementById('howto').hidden ? '' : document.getElementById('howto').innerText");
report
.lock()
.unwrap()
.push(format!("how-to shown: {howto}"));
assert!(
howto
.as_str()
.is_some_and(|h| h.contains("not a single tab")),
"Safari's how-to is missing: {howto}"
);
check_place(&mut eval);
let r = eval(
"const c = document.createElement('canvas'); c.width = 1280; c.height = 800; \
document.body.prepend(c); const g = c.getContext('2d'); let n = 0; \
(function draw() { g.fillStyle = `hsl(${n % 360},80%,50%)`; g.fillRect(0, 0, 1280, 800); \
g.fillStyle = '#fff'; g.font = '96px sans-serif'; g.fillText(String(n++), 40, 200); \
requestAnimationFrame(draw); })(); \
const a = new AudioContext({sampleRate: tvpipeShare.config.sampleRate}); await a.resume(); \
const o = a.createOscillator(); o.frequency.value = 440; \
const d = a.createMediaStreamDestination(); o.connect(d); o.start(); \
tvpipeShare.audioCtx = new AudioContext({sampleRate: tvpipeShare.config.sampleRate}); \
await tvpipeShare.audioCtx.resume(); \
const s = new MediaStream([...c.captureStream(30).getVideoTracks(), ...d.stream.getAudioTracks()]); \
return tvpipeShare.share(s).then(() => 'ok', e => 'error: ' + e);",
);
report.lock().unwrap().push(format!("share: {r}"));
watch(&mut eval, &report);
let mode = eval("return window.tvpipeLastStats && window.tvpipeLastStats.mode");
report.lock().unwrap().push(format!("engine: {mode}"));
assert_eq!(
mode.as_str(),
Some("worker"),
"Safari should encode in a worker"
);
drop(wd);
});
}