tvpipe 0.2.0

Stream a program's frames and sound, files, web pages or the screen to Apple TVs, Chromecasts and browser tabs with low latency, in process
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! `share` with the real capture script in real browsers (opt-in,
//! `--ignored`): headless Chrome driven over the DevTools protocol,
//! headless Firefox over WebDriver BiDi (tvpipe's own launcher and
//! profile, no geckodriver), and Safari over WebDriver (`safaridriver`).
//! To fake Cast + AirPlay receivers by default, or to a real one.
//!
//! ```sh
//! TVPIPE_TEST_CHROME=/path/to/chrome cargo test --release chrome_share -- --ignored --nocapture
//! TVPIPE_TEST_FIREFOX=/path/to/firefox cargo test --release firefox_share -- --ignored --nocapture
//! TVPIPE_TEST_SAFARI=1 cargo test --release safari_share -- --ignored --nocapture
//! ```
//!
//! Firefox: `TVPIPE_TEST_FIREFOX_HEADED=1` (a window),
//! `TVPIPE_TEST_FIREFOX_SCREEN=1` (the page's own getDisplayMedia, which
//! shares the primary screen without a picker; on macOS Firefox needs the
//! Screen Recording permission). The manual check with the picker is in
//! docs/share-protocol.md (Browsers).
//!
//! Options (both): `TVPIPE_TEST_BROWSER_SECS` (streaming time, default 6),
//! `_TO=ADDR` (a real receiver), `_SIZE=WxH` (`--size`), `_DUMP=PATH`
//! (what the fake Cast receiver got: H.264 Annex B, and `PATH.aac`),
//! `_DEBUG=1` (debug logs). Chrome: `TVPIPE_TEST_CHROME_VIEWPORT=WxH`
//! (default 1920x1080), `TVPIPE_TEST_CHROME_HEADED=1`,
//! `TVPIPE_TEST_CHROME_NO_MSTP=1` (the `<video>` path of Firefox).
//!
//! Safari cannot be made to accept the screen-sharing picker, so it
//! shares a synthetic stream (an animated 16:10 canvas and a tone)
//! through the same `share()`; everything after getDisplayMedia is the
//! real path. Safari needs Develop > Allow Remote Automation (once).

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)
}

/// One browser test at a time (they share the stop flag).
static SERIAL: Mutex<()> = Mutex::new(());
static STOP: std::sync::LazyLock<crate::util::stop::Stop> =
    std::sync::LazyLock::new(crate::util::stop::Stop::new);

/// Runs `share` while `drive(url, report)` works the browser on another
/// thread; the session stops when `drive` returns.
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:?}");
}

/// The page's letterbox arithmetic must be the Rust one.
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}");
    }
}

/// Streams for a while, sampling the page's stats; asks for a keyframe
/// halfway and checks the encoder made one.
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());
    }
    // Stats come every 2 s: wait for the one covering the request.
    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"
    );
}

// ---------------------------------------------------------------------------
// Chrome (DevTools protocol)

/// Chrome for the tests: `browser::launch` with a temporary profile, the
/// tab set up by `browser::headless::attach` (the production code), on
/// `url`. Dropping it quits Chrome and deletes the profile.
pub(super) struct Chrome {
    browser: crate::browser::launch::Browser,
    session: String,
    _profile: crate::browser::launch::Profile,
}

impl Chrome {
    /// A command on the tab's session; its `result`.
    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}"))
    }

    /// Evaluates a function body as if the user clicked (transient
    /// activation); awaits a returned promise.
    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()
    }
}

/// TVPIPE_TEST_CHROME_VIEWPORT=WxH, default 1920x1080.
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)
}

/// Starts Chrome on `url` (headless unless TVPIPE_TEST_CHROME_HEADED,
/// tab capture auto-accepted).
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
}

/// The real capture script in headless Chrome: tab capture of the share
/// page itself (an animation and a tone injected).
#[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);
        // Something that moves and something that sounds.
        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);
    });
}

// ---------------------------------------------------------------------------
// Firefox (WebDriver BiDi)

/// Firefox for the tests: `browser::launch` with a temporary profile and
/// tvpipe's preferences, the tab set up by
/// `browser::headless::firefox::attach` (the production code), on `url`.
/// Dropping it quits Firefox and deletes the profile.
pub(super) struct Firefox {
    browser: crate::browser::launch::Browser,
    context: String,
    profile: crate::browser::launch::Profile,
}

impl Firefox {
    /// Evaluates a function body as if the user clicked (transient
    /// activation); awaits a returned promise.
    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()
    }

    /// Opens another tab in front: this one goes to the background.
    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();
    }
}

/// TVPIPE_TEST_FIREFOX=/path/to/firefox (the executable, or a macOS
/// `.app`'s `Contents/MacOS/firefox`).
pub(super) fn firefox_bin() -> Option<String> {
    std::env::var("TVPIPE_TEST_FIREFOX").ok()
}

/// Starts Firefox on `url` (headless unless TVPIPE_TEST_FIREFOX_HEADED).
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,
    }
}

/// The real capture script and share page in Firefox: the page's own
/// tab captured (getUserMedia's `browser` source and its sound,
/// `audioCapture`: what `share URL` uses) and shared through the page's
/// engine (`<video>` frames, Firefox's H.264 encoder, the padding, the
/// audio worklet, keyframe requests). TVPIPE_TEST_FIREFOX_SCREEN=1
/// shares with the page's real getDisplayMedia instead, which tvpipe's
/// preferences answer without the picker: the primary screen.
#[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| {
        // 16:10 into the receivers' 16:9: the padding.
        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}"));
        // The share page in a background tab (the user switched to the
        // tab to show) keeps streaming.
        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);
    });
}

// ---------------------------------------------------------------------------
// Safari (WebDriver)

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,
        )
    }

    /// Runs a function body (`return` a value; promises are awaited).
    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();
    }
}

/// The real capture script in Safari, sharing a synthetic 16:10 stream
/// (getDisplayMedia needs a human): the worker engine, Safari's H.264
/// encoder, the padding, the audio worklet, keyframe requests.
#[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);
    });
}