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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
//! Finding and starting the browser for `tvpipe share URL`: a
//! Chromium-based one (driven over the DevTools protocol, [`Cdp`]) or
//! Firefox (WebDriver BiDi, `bidi`); [`Engine`] tells them apart.
//!
//! - [`find_browser`]: `--browser PATH` (or a name on `PATH`, or a macOS
//!   `.app`; `firefox` also finds an installed Firefox), `$TVPIPE_BROWSER`,
//!   the well-known install paths of Chromium-based browsers
//!   (`browser::platform`), then `PATH`, then the same for Firefox.
//! - [`Profile`]: the browser's own user-data directory: a fresh temp
//!   directory (deleted on drop) or `--profile DIR` (kept, for logins).
//!   Never the user's real browser profile.
//! - [`sweep_stale_profiles`]: temp profiles a killed tvpipe left behind
//!   (and the browsers still running on them). A temporary profile holds
//!   `tvpipe-owner`: the port of a loopback "beacon" its tvpipe answers on
//!   with a random nonce while it runs; no answer means its tvpipe is
//!   gone. A browser still on such a profile is asked to quit through the
//!   DevTools endpoint its own `DevToolsActivePort` names (the path holds
//!   that browser instance's id, so no other browser can answer it), or
//!   Firefox through the BiDi port its `WebDriverBiDiServer.json` names.
//! - [`Browser::launch`]: starts it with `--remote-debugging-port=0`,
//!   reads the port from `DevToolsActivePort` (Firefox:
//!   `WebDriverBiDiServer.json`) in the profile, connects [`Cdp`] to the
//!   browser endpoint (Firefox: a BiDi session). [`Browser::close`] (and
//!   drop) asks it to quit (`Browser.close`, `browser.close`), waits,
//!   then kills it.
//! - Firefox's preferences ([`FIREFOX_PREFS`], written to the profile's
//!   `user.js`): no permission prompts, the old getUserMedia tab and
//!   tab-audio capture sources on, autoplay allowed, its own sound muted.
//!
//! Sources: Chrome DevTools Protocol docs; Chromium command-line switches
//! (`--remote-debugging-port`, `--user-data-dir`, `--headless`,
//! `--auto-accept-this-tab-capture`, `--autoplay-policy`, ...); Firefox's
//! command line (`--profile`, `--headless`, `--remote-debugging-port`) and
//! preferences (modules/libpref/init/StaticPrefList.yaml).

use std::collections::VecDeque;
use std::ffi::OsString;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crate::browser::cdp::Cdp;
use crate::browser::{bidi, platform};
use crate::codec::json::Value;
use crate::error::{Error, Result};

/// The environment variable naming the browser (like `--browser`).
pub const BROWSER_ENV: &str = "TVPIPE_BROWSER";
/// How long the browser may take to open its DevTools port.
const START_TIMEOUT: Duration = Duration::from_secs(30);
/// How long a browser asked to quit may take before it is killed.
const QUIT_TIMEOUT: Duration = Duration::from_secs(5);
/// Lines of the browser's stderr kept for error messages.
const STDERR_TAIL: usize = 20;

/// The kind of browser, which decides how tvpipe drives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Engine {
    /// Chrome, Edge, Chromium, Brave: the DevTools protocol.
    Chromium,
    /// Firefox: WebDriver BiDi.
    Firefox,
}

impl Engine {
    /// By the executable's name: Firefox's has `firefox` in it
    /// (`firefox`, `firefox-esr`, `firefox.exe`); anything else is taken
    /// for a Chromium-based browser.
    pub fn of(bin: &Path) -> Engine {
        let name = bin
            .file_name()
            .map(|n| n.to_string_lossy().to_ascii_lowercase())
            .unwrap_or_default();
        if name.contains("firefox") {
            Engine::Firefox
        } else {
            Engine::Chromium
        }
    }
}

/// Finds a Chromium-based browser or Firefox (see the module docs for the
/// order).
pub fn find_browser(explicit: Option<&Path>) -> Result<PathBuf> {
    find_with(explicit, &|k| std::env::var_os(k), &|p| p.is_file())
}

fn find_with(
    explicit: Option<&Path>,
    env: &dyn Fn(&str) -> Option<OsString>,
    exists: &dyn Fn(&Path) -> bool,
) -> Result<PathBuf> {
    let path_dirs: Vec<PathBuf> = env("PATH")
        .map(|p| std::env::split_paths(&p).collect())
        .unwrap_or_default();
    let on_path = |name: &Path| -> Option<PathBuf> {
        path_dirs
            .iter()
            .map(|d| d.join(name))
            .find(|p| exists(p))
            .or_else(|| {
                // `msedge` for `msedge.exe` on Windows.
                let suffix = std::env::consts::EXE_SUFFIX;
                let mut with = name.as_os_str().to_owned();
                with.push(suffix);
                (!suffix.is_empty() && name.extension().is_none())
                    .then(|| path_dirs.iter().map(|d| d.join(&with)).find(|p| exists(p)))
                    .flatten()
            })
    };
    let firefox = || {
        platform::firefox_install_paths(env)
            .into_iter()
            .find(|p| exists(p))
            .or_else(|| {
                platform::firefox_names()
                    .iter()
                    .find_map(|n| on_path(Path::new(n)))
            })
    };
    let given = |p: &Path, what: &str| -> Result<PathBuf> {
        if exists(p) {
            return Ok(p.to_path_buf());
        }
        if let Some(exe) = app_bundle_executable(p).into_iter().find(|e| exists(e)) {
            return Ok(exe);
        }
        if p.components().count() == 1 {
            if let Some(found) = on_path(p) {
                return Ok(found);
            }
            if p.as_os_str().eq_ignore_ascii_case("firefox") {
                if let Some(found) = firefox() {
                    return Ok(found);
                }
            }
        }
        Err(Error::not_found(format!(
            "{what} {}: no such browser executable",
            p.display()
        )))
    };
    if let Some(p) = explicit {
        return given(p, "--browser");
    }
    if let Some(p) = env(BROWSER_ENV).filter(|v| !v.is_empty()) {
        return given(Path::new(&p), &format!("${BROWSER_ENV}"));
    }
    if let Some(p) = platform::browser_install_paths(env)
        .into_iter()
        .find(|p| exists(p))
    {
        return Ok(p);
    }
    if let Some(p) = platform::browser_names()
        .iter()
        .find_map(|n| on_path(Path::new(n)))
    {
        return Ok(p);
    }
    if let Some(p) = firefox() {
        return Ok(p);
    }
    Err(Error::not_found(format!(
        "no browser found (Chrome, Edge, Chromium, Brave or Firefox); \
         install one or name it with --browser PATH or ${BROWSER_ENV}"
    )))
}

/// `X.app` → `X.app/Contents/MacOS/X`, or `.../firefox` (Firefox's
/// bundles, `Firefox Nightly.app` too, name it so): a macOS bundle given
/// as the browser.
fn app_bundle_executable(p: &Path) -> Vec<PathBuf> {
    let Some(name) = p
        .file_name()
        .and_then(|n| n.to_str())
        .and_then(|n| n.strip_suffix(".app"))
    else {
        return Vec::new();
    };
    let dir = p.join("Contents/MacOS");
    vec![dir.join(name), dir.join("firefox")]
}

/// Name prefix of temporary profiles (the only directories the sweep
/// touches).
const TEMP_PREFIX: &str = "tvpipe-browser-";
/// In a temporary profile: `PID PORT NONCE` of its tvpipe's beacon.
const OWNER_FILE: &str = "tvpipe-owner";
/// A temporary profile without an owner file is left alone this long
/// (its tvpipe may be creating it).
const ORPHAN_AGE: Duration = Duration::from_secs(120);

/// The browser's user-data directory.
#[derive(Debug)]
pub struct Profile {
    dir: PathBuf,
    temporary: bool,
    beacon: Option<Beacon>,
}

impl Profile {
    /// A fresh directory under the system's temp directory, deleted when
    /// dropped.
    pub fn temporary() -> Result<Profile> {
        Profile::temporary_in(&std::env::temp_dir())
    }

    fn temporary_in(root: &Path) -> Result<Profile> {
        let nonce = crate::util::hex::encode(&crate::crypto::ring::random_array::<16>()?);
        let dir = root.join(format!("{TEMP_PREFIX}{}", &nonce[..12]));
        std::fs::create_dir(&dir).map_err(|e| Error::io(format!("create {}", dir.display()), e))?;
        let mut p = Profile {
            dir,
            temporary: true,
            beacon: None,
        };
        let beacon = Beacon::start(nonce.clone())?;
        let owner = format!("{} {} {nonce}\n", std::process::id(), beacon.port);
        p.beacon = Some(beacon);
        std::fs::write(p.dir.join(OWNER_FILE), owner)
            .map_err(|e| Error::io(format!("write {}", p.dir.display()), e))?;
        Ok(p)
    }

    /// `--profile DIR`: kept across runs (logins, cookies). Refuses the
    /// browsers' own default profiles.
    pub fn persistent(dir: &Path) -> Result<Profile> {
        std::fs::create_dir_all(dir)
            .map_err(|e| Error::io(format!("create {}", dir.display()), e))?;
        let dir = std::fs::canonicalize(dir)
            .map_err(|e| Error::io(format!("resolve {}", dir.display()), e))?;
        let real = platform::default_profile_dirs(&|k| std::env::var_os(k));
        check_not_real(&dir, &real)?;
        Ok(Profile {
            dir,
            temporary: false,
            beacon: None,
        })
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }
}

/// Refuses `dir` if it is (or is inside, or holds) a browser's own
/// profile directory.
fn check_not_real(dir: &Path, real: &[PathBuf]) -> Result<()> {
    for r in real {
        let r = std::fs::canonicalize(r).unwrap_or_else(|_| r.clone());
        if dir.starts_with(&r) || r.starts_with(dir) {
            return Err(Error::usage(format!(
                "--profile {}: that is (or holds) a browser's own profile ({}); \
                 tvpipe uses a separate one: pick an empty directory",
                dir.display(),
                r.display()
            )));
        }
    }
    Ok(())
}

impl Drop for Profile {
    fn drop(&mut self) {
        self.beacon = None;
        if !self.temporary {
            return;
        }
        // Helper processes may still write for a moment after the
        // browser quit.
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            match std::fs::remove_dir_all(&self.dir) {
                Ok(()) => return,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
                Err(e) if Instant::now() >= deadline => {
                    warn!("cannot delete {}: {e}", self.dir.display());
                    return;
                }
                Err(_) => std::thread::sleep(Duration::from_millis(100)),
            }
        }
    }
}

/// Answers connections on a loopback port with `nonce` while its
/// tvpipe runs (see the module docs).
#[derive(Debug)]
struct Beacon {
    port: u16,
    stop: Arc<AtomicBool>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl Beacon {
    fn start(nonce: String) -> Result<Beacon> {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
            .map_err(|e| Error::io("bind the profile beacon", e))?;
        let port = listener
            .local_addr()
            .map_err(|e| Error::io("profile beacon address", e))?
            .port();
        let stop = Arc::new(AtomicBool::new(false));
        let st = stop.clone();
        let thread = std::thread::Builder::new()
            .name("profile-beacon".into())
            .spawn(move || {
                for conn in listener.incoming() {
                    if st.load(Ordering::SeqCst) {
                        return;
                    }
                    if let Ok(mut c) = conn {
                        let _ = c.set_write_timeout(Some(Duration::from_secs(1)));
                        let _ = c.write_all(nonce.as_bytes());
                    }
                }
            })
            .map_err(|e| Error::io("spawn the profile beacon", e))?;
        Ok(Beacon {
            port,
            stop,
            thread: Some(thread),
        })
    }
}

impl Drop for Beacon {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::SeqCst);
        // Wake the blocking accept (if that fails, the thread is left
        // behind rather than hanging the exit).
        let _ = TcpStream::connect_timeout(
            &(Ipv4Addr::LOCALHOST, self.port).into(),
            Duration::from_secs(1),
        );
        if let Some(t) = self.thread.take() {
            crate::util::thread::join_until(t, Instant::now() + Duration::from_secs(2));
        }
    }
}

/// Removes the temporary profiles in the system's temp directory whose
/// tvpipe is gone (killed before it could clean up), after asking a
/// browser still running on one to quit. Returns how many it removed.
pub fn sweep_stale_profiles() -> usize {
    sweep_in(&std::env::temp_dir(), ORPHAN_AGE)
}

fn sweep_in(root: &Path, orphan_age: Duration) -> usize {
    let Ok(entries) = std::fs::read_dir(root) else {
        return 0;
    };
    let mut removed = 0;
    for e in entries.flatten() {
        if !e.file_name().to_string_lossy().starts_with(TEMP_PREFIX)
            || !e.file_type().is_ok_and(|t| t.is_dir())
        {
            continue;
        }
        let dir = e.path();
        let closed = match owner(&dir, orphan_age) {
            Owner::Alive => continue,
            // Made by a tvpipe without beacons (or being made): only
            // removed when no browser runs on it.
            Owner::Unknown if browser_answers(&dir) => continue,
            Owner::Unknown => Ok(false),
            Owner::Gone => close_stale_browser(&dir),
        };
        let closed = match closed {
            Ok(closed) => closed,
            Err(e) => {
                warn!(
                    "browser: {} was left by an earlier run, but its browser {e}; leaving it",
                    dir.display()
                );
                continue;
            }
        };
        let deadline = Instant::now() + Duration::from_secs(2);
        let gone = loop {
            match std::fs::remove_dir_all(&dir) {
                Ok(()) => break true,
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => break true,
                Err(_) if Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(100))
                }
                Err(e) => {
                    debug!("browser: cannot delete {}: {e}", dir.display());
                    break false;
                }
            }
        };
        if gone {
            removed += 1;
            info!(
                "browser: removed {} left by an earlier run{}",
                dir.display(),
                if closed {
                    " (and quit its browser)"
                } else {
                    ""
                }
            );
        }
    }
    removed
}

/// Whether the tvpipe that made a temporary profile still runs.
#[derive(Debug, PartialEq, Eq)]
enum Owner {
    /// Its beacon answers (or the directory is being made).
    Alive,
    /// Its beacon does not answer, or the owner file is garbage.
    Gone,
    /// No owner file and older than the orphan age.
    Unknown,
}

fn owner(dir: &Path, orphan_age: Duration) -> Owner {
    let Ok(owner) = std::fs::read_to_string(dir.join(OWNER_FILE)) else {
        let age = std::fs::metadata(dir)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.elapsed().ok());
        return if age.is_none_or(|a| a < orphan_age) {
            Owner::Alive
        } else {
            Owner::Unknown
        };
    };
    let mut f = owner.split_whitespace();
    let (_pid, port, nonce) = (f.next(), f.next(), f.next());
    match (port.and_then(|p| p.parse::<u16>().ok()), nonce) {
        (Some(port), Some(nonce)) if beacon_answers(port, nonce) => Owner::Alive,
        _ => Owner::Gone,
    }
}

/// The endpoint of a browser that may still run on profile `dir`: its
/// engine, port and WebSocket URL (Chromium's `DevToolsActivePort`,
/// Firefox's `WebDriverBiDiServer.json`).
fn stale_endpoint(dir: &Path) -> Option<(Engine, u16, String)> {
    if let Some((port, path)) = std::fs::read_to_string(dir.join("DevToolsActivePort"))
        .ok()
        .and_then(|s| parse_active_port(&s))
    {
        return Some((
            Engine::Chromium,
            port,
            format!("ws://127.0.0.1:{port}{path}"),
        ));
    }
    let port = bidi::server_file(dir)?;
    Some((Engine::Firefox, port, bidi::session_url(port)))
}

/// Whether a browser answers on the endpoint `dir` names.
fn browser_answers(dir: &Path) -> bool {
    stale_endpoint(dir)
        .is_some_and(|(_, _, url)| Cdp::connect(&url, Duration::from_secs(2)).is_ok())
}

fn beacon_answers(port: u16, nonce: &str) -> bool {
    let addr = (Ipv4Addr::LOCALHOST, port).into();
    let Ok(mut c) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else {
        return false;
    };
    let _ = c.set_read_timeout(Some(Duration::from_secs(1)));
    let mut got = Vec::new();
    let _ = Read::by_ref(&mut c).take(64).read_to_end(&mut got);
    got == nonce.as_bytes()
}

/// Asks a browser still running on the stale profile `dir` to quit, by
/// the DevTools endpoint in its `DevToolsActivePort`. `Ok(true)`: one
/// quit; `Ok(false)`: none answers; an error: one answers but does not
/// quit.
fn close_stale_browser(dir: &Path) -> Result<bool> {
    let Some((engine, port, url)) = stale_endpoint(dir) else {
        return Ok(false);
    };
    let Ok(cdp) = Cdp::connect(&url, Duration::from_secs(2)) else {
        return Ok(false);
    };
    // Firefox still holds the dead tvpipe's BiDi session: Marionette.
    let marionette = (engine == Engine::Firefox)
        .then(|| bidi::marionette_port(dir))
        .flatten();
    match marionette {
        Some(m) => {
            if let Err(e) = bidi::marionette_quit(m, Duration::from_secs(2)) {
                debug!("browser: marionette: {e}");
            }
        }
        None => ask_to_quit(&cdp, engine),
    }
    drop(cdp);
    // Gone once its DevTools port refuses connections.
    let deadline = Instant::now() + QUIT_TIMEOUT;
    let addr = (Ipv4Addr::LOCALHOST, port).into();
    while TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
        if Instant::now() >= deadline {
            return Err(Error::timeout("does not quit"));
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    // Its helper processes follow it.
    std::thread::sleep(Duration::from_millis(300));
    Ok(true)
}

/// Asks the browser on `rpc` to quit (without waiting for it). Firefox
/// takes the command in a session only (ours, or a new one if it has
/// none).
fn ask_to_quit(rpc: &Cdp, engine: Engine) {
    let wait = Duration::from_secs(2);
    match engine {
        Engine::Chromium => {
            let _ = rpc.call_timeout(None, "Browser.close", Value::object(), wait);
        }
        Engine::Firefox => {
            // In a session of ours, or a new one.
            if rpc
                .call_timeout(None, "browser.close", Value::object(), wait)
                .is_err()
                && bidi::new_session(rpc).is_ok()
            {
                let _ = rpc.call_timeout(None, "browser.close", Value::object(), wait);
            }
        }
    }
}

/// How to start the browser.
#[derive(Debug, Clone)]
pub struct LaunchOptions {
    pub bin: PathBuf,
    /// The page's viewport (CSS pixels at scale 1): the stream size.
    pub viewport: (u32, u32),
    /// A normal window instead of `--headless=new`.
    pub visible: bool,
    /// `tvpipe screen`: a normal window whose page captures the desktop.
    pub screen: Option<ScreenLaunch>,
}

/// How `tvpipe screen` starts the browser (`browser::screen`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScreenLaunch {
    /// Switches that answer the screen picker (`--auto-select-...`).
    pub switches: Vec<String>,
    /// Leave the window behind the others (macOS: `open -g`); the picker
    /// is answered by a switch.
    pub background: bool,
}

impl LaunchOptions {
    pub fn engine(&self) -> Engine {
        Engine::of(&self.bin)
    }
}

/// Firefox's preferences for tvpipe's profile (`user.js`). Firefox's
/// remote agent adds its own automation defaults (no first-run pages, no
/// update checks, ...).
pub const FIREFOX_PREFS: &[(&str, &str)] = &[
    // The Marionette port in MarionetteActivePort (for the sweep,
    // `bidi::marionette_quit`).
    ("marionette.port", "0"),
    // getUserMedia without a prompt, and its sources for this tab's
    // picture ('browser') and sound ('audioCapture'): Firefox's
    // getDisplayMedia has no tab capture and no audio (capture.js).
    ("media.navigator.permission.disabled", "true"),
    ("media.getusermedia.browser.enabled", "true"),
    ("media.getusermedia.audio.capture.enabled", "true"),
    // Sound and video play without a click.
    ("media.autoplay.default", "0"),
    ("media.autoplay.blocking_policy", "0"),
    // The captured sound is taken before the output: mute the output
    // (the TV plays it).
    ("media.volume_scale", "\"0.0\""),
    // Pages from the internet may reach tvpipe on 127.0.0.1 (Local
    // Network Access).
    ("network.lna.enabled", "false"),
    ("network.lna.blocking", "false"),
    // Navigations and reloads never wait for a "leave this page?" prompt.
    ("dom.disable_beforeunload", "true"),
    // No hidden preloaded new-tab page beside the page's tab.
    ("browser.newtab.preload", "false"),
    // A restarted browser opens the page, not a restore or safe-mode
    // question.
    ("browser.sessionstore.resume_from_crash", "false"),
    ("toolkit.startup.max_resumed_crashes", "-1"),
    // The page keeps its timers and painting in a window behind others.
    ("dom.timeout.enable_budget_timer_throttling", "false"),
    ("widget.windows.window_occlusion_tracking.enabled", "false"),
];

/// `user.js` with [`FIREFOX_PREFS`].
pub fn firefox_user_js() -> String {
    let mut s = String::from("// Written by tvpipe for 'tvpipe share URL'.\n");
    for (k, v) in FIREFOX_PREFS {
        s.push_str(&format!("user_pref(\"{k}\", {v});\n"));
    }
    s
}

/// The command line for `opts` with profile `dir`, opening `about:blank`
/// (the caller sets the page up before it loads the real URL).
pub fn args(opts: &LaunchOptions, dir: &Path) -> Vec<OsString> {
    if opts.engine() == Engine::Firefox {
        return firefox_args(opts, dir);
    }
    if let Some(screen) = &opts.screen {
        return screen_args(opts.viewport, screen, dir);
    }
    let (w, h) = opts.viewport;
    let mut a: Vec<OsString> = Vec::new();
    if !opts.visible {
        a.push("--headless=new".into());
        // Headless tab capture is clamped to the screen (800x600 unless
        // told otherwise).
        a.push(format!("--screen-info={{0,0 {w}x{h}}}").into());
    }
    let mut dir_arg = OsString::from("--user-data-dir=");
    dir_arg.push(dir);
    a.push(dir_arg);
    for s in [
        "--remote-debugging-port=0",
        // A profile of its own: no first-run UI, no default-browser
        // question, no keychain prompt (macOS) or keyring (Linux).
        "--no-first-run",
        "--no-default-browser-check",
        "--use-mock-keychain",
        "--password-store=basic",
        // getDisplayMedia({preferCurrentTab}) shares this tab without a
        // picker; sound plays without a click.
        "--auto-accept-this-tab-capture",
        "--autoplay-policy=no-user-gesture-required",
        // The captured tab keeps its timers and frame rate when hidden
        // or covered (a visible window behind others).
        "--disable-background-timer-throttling",
        "--disable-renderer-backgrounding",
        "--disable-backgrounding-occluded-windows",
        "--force-device-scale-factor=1",
    ] {
        a.push(s.into());
    }
    // The window is resized to the exact viewport once it is up.
    a.push(format!("--window-size={w},{h}").into());
    a.push("about:blank".into());
    a
}

/// Firefox's command line (the viewport is set over BiDi).
fn firefox_args(opts: &LaunchOptions, dir: &Path) -> Vec<OsString> {
    let (w, h) = opts.viewport;
    let mut a: Vec<OsString> = Vec::new();
    if !opts.visible {
        a.push("--headless".into());
    }
    a.push("--profile".into());
    a.push(dir.into());
    for s in [
        "--no-remote",
        "--new-instance",
        "--remote-debugging-port=0",
        "--marionette",
    ] {
        a.push(s.into());
    }
    a.push(format!("--window-size={w},{h}").into());
    a.push("about:blank".into());
    a
}

/// The command line of `tvpipe screen`'s browser: a small normal window
/// (desktop capture needs a real one, and getDisplayMedia a visible tab),
/// the picker answered by `screen.switches`, system audio ticked.
fn screen_args(window: (u32, u32), screen: &ScreenLaunch, dir: &Path) -> Vec<OsString> {
    let mut dir_arg = OsString::from("--user-data-dir=");
    dir_arg.push(dir);
    let mut a: Vec<OsString> = vec![dir_arg];
    for s in [
        "--remote-debugging-port=0",
        "--no-first-run",
        "--no-default-browser-check",
        "--use-mock-keychain",
        "--password-store=basic",
        // The capture page keeps capturing and encoding once its window
        // is minimized.
        "--disable-background-timer-throttling",
        "--disable-renderer-backgrounding",
        "--disable-backgrounding-occluded-windows",
        // The picker's "Also share system audio" ticked (when it is
        // answered by a switch, nobody can tick it). The underscore is
        // Chrome's spelling.
        "--system-audio-capture-default_checked",
        // Linux: system audio through PulseAudio/PipeWire's monitor of the
        // output (off by default in Chrome).
        "--enable-features=PulseaudioLoopbackForScreenShare",
        // English source names ("Screen 2") for --display N (not on macOS,
        // where the system language decides).
        "--lang=en-US",
    ] {
        a.push(s.into());
    }
    a.extend(screen.switches.iter().map(OsString::from));
    a.push(format!("--window-size={},{}", window.0, window.1).into());
    a.push("about:blank".into());
    a
}

/// A running browser and its DevTools (Firefox: WebDriver BiDi)
/// connection.
pub struct Browser {
    child: Option<Child>,
    /// Started as an app of its own (macOS `tvpipe screen`): no child of
    /// ours.
    detached: Option<Detached>,
    cdp: Cdp,
    pub engine: Engine,
    /// The product (`Chrome/157.0...`, `HeadlessChrome/...`,
    /// `Firefox/160.0`).
    pub product: String,
    pub user_agent: String,
    stderr: Arc<Mutex<VecDeque<String>>>,
}

/// A browser started through `platform::own_app_command`.
struct Detached {
    /// Its process (from DevTools), to kill it if it does not quit.
    pid: Option<u32>,
    /// Its DevTools port: open while it runs.
    port: u16,
    /// Where `open` sends its stderr.
    stderr: PathBuf,
}

impl Browser {
    /// Starts the browser with `profile` and connects to it.
    pub fn launch(opts: &LaunchOptions, profile: &Profile) -> Result<Browser> {
        let engine = opts.engine();
        let port_file = profile.dir().join(match engine {
            Engine::Chromium => "DevToolsActivePort",
            Engine::Firefox => bidi::SERVER_FILE,
        });
        // A persistent profile may hold the last run's.
        let _ = std::fs::remove_file(&port_file);
        if engine == Engine::Firefox {
            let _ = std::fs::remove_file(profile.dir().join(bidi::MARIONETTE_FILE));
            let user_js = profile.dir().join("user.js");
            std::fs::write(&user_js, firefox_user_js())
                .map_err(|e| Error::io(format!("write {}", user_js.display()), e))?;
        }
        debug!(
            "browser: starting {} with profile {}",
            opts.bin.display(),
            profile.dir().display()
        );
        let argv = args(opts, profile.dir());
        let stderr_file = profile.dir().join("tvpipe-stderr.log");
        if let Some(mut open) = opts
            .screen
            .as_ref()
            .and_then(|s| platform::own_app_command(&opts.bin, &argv, s.background, &stderr_file))
        {
            return Browser::launch_detached(&mut open, &port_file, stderr_file);
        }
        let mut child = Command::new(&opts.bin)
            .args(argv)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| Error::io(format!("start {}", opts.bin.display()), e))?;
        let stderr: Arc<Mutex<VecDeque<String>>> = Arc::default();
        if let Some(err) = child.stderr.take() {
            let tail = stderr.clone();
            let _ = std::thread::Builder::new()
                .name("browser-stderr".into())
                .spawn(move || {
                    for line in BufReader::new(err).lines() {
                        let Ok(line) = line else { return };
                        trace!("browser stderr: {line}");
                        let mut t = tail.lock().unwrap_or_else(|e| e.into_inner());
                        if t.len() >= STDERR_TAIL {
                            t.pop_front();
                        }
                        t.push_back(line);
                    }
                });
        }
        let tail = |stderr: &Arc<Mutex<VecDeque<String>>>| {
            let t = stderr.lock().unwrap_or_else(|e| e.into_inner());
            t.iter()
                .rev()
                .find(|l| !l.trim().is_empty())
                .map(|l| format!(": {}", l.trim()))
                .unwrap_or_default()
        };
        let deadline = Instant::now() + START_TIMEOUT;
        let (port, url) = loop {
            let found = match engine {
                Engine::Chromium => std::fs::read_to_string(&port_file)
                    .ok()
                    .and_then(|s| parse_active_port(&s))
                    .map(|(port, path)| (port, format!("ws://127.0.0.1:{port}{path}"))),
                Engine::Firefox => {
                    bidi::server_file(profile.dir()).map(|port| (port, bidi::session_url(port)))
                }
            };
            if let Some(p) = found {
                break p;
            }
            if let Ok(Some(status)) = child.try_wait() {
                // Give the stderr reader a moment to catch the last line.
                std::thread::sleep(Duration::from_millis(100));
                return Err(Error::process(format!(
                    "the browser exited at once ({status}){}; is another browser \
                     using the same --profile?",
                    tail(&stderr)
                )));
            }
            if Instant::now() >= deadline {
                kill(&mut child);
                return Err(Error::timeout(format!(
                    "the browser did not open its remote debugging port within {} s{}",
                    START_TIMEOUT.as_secs(),
                    tail(&stderr)
                )));
            }
            std::thread::sleep(Duration::from_millis(50));
        };
        let cdp = match Cdp::connect(&url, Duration::from_secs(10)) {
            Ok(c) => c,
            Err(e) => {
                kill(&mut child);
                return Err(e);
            }
        };
        let mut b = Browser {
            child: Some(child),
            detached: None,
            cdp,
            engine,
            product: String::new(),
            user_agent: String::new(),
            stderr,
        };
        b.identify(port)?;
        Ok(b)
    }

    /// Reads the product and user agent (Firefox: in a new BiDi session).
    fn identify(&mut self, port: u16) -> Result<()> {
        match self.engine {
            Engine::Chromium => {
                let v = self.cdp.call(None, "Browser.getVersion", Value::object())?;
                let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_owned();
                self.product = s("product");
                self.user_agent = s("userAgent");
                debug!("browser: {} on DevTools port {port}", self.product);
            }
            Engine::Firefox => {
                let info = bidi::new_session(&self.cdp)?;
                self.product = info.product;
                self.user_agent = info.user_agent;
                debug!("browser: {} on WebDriver BiDi port {port}", self.product);
            }
        }
        Ok(())
    }

    /// Starts the browser with `open` (it is no child of ours) and
    /// connects to it.
    fn launch_detached(open: &mut Command, port_file: &Path, stderr: PathBuf) -> Result<Browser> {
        debug!("browser: starting it as an app of its own: {open:?}");
        let status = open
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .output()
            .map_err(|e| Error::io("run open", e))?;
        if !status.status.success() {
            return Err(Error::process(format!(
                "open could not start the browser ({}): {}",
                status.status,
                String::from_utf8_lossy(&status.stderr).trim()
            )));
        }
        let deadline = Instant::now() + START_TIMEOUT;
        let (port, path) = loop {
            if let Some(p) = std::fs::read_to_string(port_file)
                .ok()
                .and_then(|s| parse_active_port(&s))
            {
                break p;
            }
            if Instant::now() >= deadline {
                return Err(Error::timeout(format!(
                    "the browser did not open its DevTools port within {} s{}",
                    START_TIMEOUT.as_secs(),
                    last_line_of(&stderr)
                        .map(|l| format!(": {l}"))
                        .unwrap_or_default()
                )));
            }
            std::thread::sleep(Duration::from_millis(50));
        };
        let url = format!("ws://127.0.0.1:{port}{path}");
        let cdp = Cdp::connect(&url, Duration::from_secs(10))?;
        let mut b = Browser {
            child: None,
            detached: Some(Detached {
                pid: None,
                port,
                stderr,
            }),
            cdp,
            engine: Engine::Chromium,
            product: String::new(),
            user_agent: String::new(),
            stderr: Arc::default(),
        };
        // Its process id, to kill it should it not quit.
        let pid = b
            .cdp
            .call(None, "SystemInfo.getProcessInfo", Value::object())
            .ok()
            .and_then(|v| {
                v.get("processInfo")?
                    .as_array()?
                    .iter()
                    .find(|p| p.get("type").and_then(Value::as_str) == Some("browser"))?
                    .get("id")?
                    .as_u64()
            })
            .and_then(|p| u32::try_from(p).ok());
        if let Some(d) = &mut b.detached {
            d.pid = pid;
        }
        b.identify(port)?;
        Ok(b)
    }

    pub fn cdp(&self) -> &Cdp {
        &self.cdp
    }

    /// The browser's exit status, if it exited.
    pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
        self.child
            .as_mut()
            .and_then(|c| c.try_wait().ok().flatten())
    }

    /// The last line the browser wrote to stderr.
    pub fn last_error_line(&self) -> Option<String> {
        if let Some(d) = &self.detached {
            return last_line_of(&d.stderr);
        }
        let t = self.stderr.lock().unwrap_or_else(|e| e.into_inner());
        t.iter().rev().find(|l| !l.trim().is_empty()).cloned()
    }

    /// Whether the browser runs as an app of its own (no exit status).
    pub fn is_detached(&self) -> bool {
        self.detached.is_some()
    }

    /// Asks the browser to quit, waits for it, kills it if it does not.
    pub fn close(&mut self) {
        if let Some(d) = self.detached.take() {
            close_detached(&self.cdp, &d);
            return;
        }
        let Some(mut child) = self.child.take() else {
            return;
        };
        if matches!(child.try_wait(), Ok(None)) {
            ask_to_quit(&self.cdp, self.engine);
        }
        let deadline = Instant::now() + QUIT_TIMEOUT;
        loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    debug!("browser: exited ({status})");
                    return;
                }
                Ok(None) if Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(50))
                }
                _ => {
                    warn!("browser: did not quit; killing it");
                    kill(&mut child);
                    return;
                }
            }
        }
    }
}

impl Drop for Browser {
    fn drop(&mut self) {
        self.close();
    }
}

fn kill(child: &mut Child) {
    let _ = child.kill();
    let _ = child.wait();
}

/// Quits a browser that is no child of ours: `Browser.close`, then waits
/// for its DevTools port to close, then kills its process.
fn close_detached(cdp: &Cdp, d: &Detached) {
    let addr = (Ipv4Addr::LOCALHOST, d.port).into();
    let running = || TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok();
    if !running() {
        return;
    }
    let _ = cdp.call_timeout(
        None,
        "Browser.close",
        Value::object(),
        Duration::from_secs(2),
    );
    let deadline = Instant::now() + QUIT_TIMEOUT;
    while running() {
        if Instant::now() >= deadline {
            warn!("browser: did not quit; killing it");
            if let Some(pid) = d.pid {
                platform::kill_pid(pid);
            }
            return;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    debug!("browser: quit");
    // Its helper processes follow it.
    std::thread::sleep(Duration::from_millis(300));
}

/// The last non-empty line of a log file.
fn last_line_of(path: &Path) -> Option<String> {
    let s = std::fs::read_to_string(path).ok()?;
    s.lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .map(|l| l.trim().to_owned())
}

/// `DevToolsActivePort`: the port on the first line, the browser
/// endpoint's path on the second.
fn parse_active_port(s: &str) -> Option<(u16, String)> {
    let mut lines = s.lines();
    let port: u16 = lines.next()?.trim().parse().ok().filter(|&p| p > 0)?;
    let path = lines.next()?.trim();
    path.starts_with("/devtools/browser/")
        .then(|| (port, path.to_owned()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    fn env_of(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<OsString> {
        let m: HashMap<String, OsString> = vars
            .iter()
            .map(|(k, v)| (k.to_string(), OsString::from(v)))
            .collect();
        move |k| m.get(k).cloned()
    }

    fn files(list: &[&str]) -> impl Fn(&Path) -> bool {
        let set: Vec<PathBuf> = list.iter().map(PathBuf::from).collect();
        move |p| set.iter().any(|f| f == p)
    }

    fn path_var(dirs: &[&str]) -> String {
        std::env::join_paths(dirs).unwrap().into_string().unwrap()
    }

    #[test]
    fn explicit_and_env_come_first() {
        let path = path_var(&["/usr/bin"]);
        let env = env_of(&[("PATH", &path), (BROWSER_ENV, "/opt/env/chrome")]);
        let exists = files(&["/opt/mine/chrome", "/opt/env/chrome", "/usr/bin/chromium"]);
        let mine = Path::new("/opt/mine/chrome");
        assert_eq!(find_with(Some(mine), &env, &exists).unwrap(), mine);
        assert_eq!(
            find_with(None, &env, &exists).unwrap(),
            Path::new("/opt/env/chrome")
        );
        // A missing explicit browser is an error, not a fallback.
        let e = find_with(Some(Path::new("/nope/chrome")), &env, &exists).unwrap_err();
        assert!(e.to_string().contains("--browser /nope/chrome"), "{e}");
        let env2 = env_of(&[("PATH", &path), (BROWSER_ENV, "/nope")]);
        assert!(find_with(None, &env2, &exists)
            .unwrap_err()
            .to_string()
            .contains(BROWSER_ENV));
        // A bare name is looked up on PATH.
        assert_eq!(
            find_with(Some(Path::new("chromium")), &env, &exists).unwrap(),
            Path::new("/usr/bin/chromium")
        );
    }

    #[test]
    fn engines() {
        for (p, e) in [
            (
                "/Applications/Firefox.app/Contents/MacOS/firefox",
                Engine::Firefox,
            ),
            ("/usr/lib/firefox-esr/firefox-esr", Engine::Firefox),
            (
                r"C:\Program Files\Mozilla Firefox\firefox.exe",
                Engine::Firefox,
            ),
            ("FIREFOX", Engine::Firefox),
            ("/opt/google/chrome/chrome", Engine::Chromium),
            (
                "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
                Engine::Chromium,
            ),
            ("msedge.exe", Engine::Chromium),
        ] {
            assert_eq!(Engine::of(Path::new(p)), e, "{p}");
        }
    }

    #[test]
    fn firefox_is_found() {
        let home = if cfg!(windows) {
            r"C:\Users\me"
        } else {
            "/home/me"
        };
        let vars = [
            ("HOME", home),
            ("ProgramFiles", r"C:\Program Files"),
            ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
        ];
        let installed = platform::firefox_install_paths(&env_of(&vars));
        assert!(!installed.is_empty());
        let ff = installed[0].to_string_lossy().into_owned();
        let path = path_var(&["/usr/bin"]);
        let mut with_path = vars.to_vec();
        with_path.push(("PATH", &path));
        let env = env_of(&with_path);
        // Only Firefox installed: auto-detected.
        assert_eq!(find_with(None, &env, &files(&[&ff])).unwrap(), installed[0]);
        // A Chromium-based browser comes first.
        let chrome = platform::browser_install_paths(&env)[0].clone();
        let both = files(&[&ff, &chrome.to_string_lossy()]);
        assert_eq!(find_with(None, &env, &both).unwrap(), chrome);
        // `--browser firefox`: on PATH, else installed.
        let name = platform::firefox_names()[0];
        let on_path = Path::new("/usr/bin").join(name);
        let on_path = on_path.to_string_lossy().into_owned();
        assert_eq!(
            find_with(Some(Path::new("firefox")), &env, &both).unwrap(),
            installed[0]
        );
        assert_eq!(
            find_with(
                Some(Path::new("Firefox")),
                &env,
                &files(&[&ff, &on_path, &chrome.to_string_lossy()])
            )
            .unwrap(),
            installed[0]
        );
        if !cfg!(windows) {
            assert_eq!(
                find_with(Some(Path::new("firefox")), &env, &files(&[&on_path])).unwrap(),
                Path::new(&on_path)
            );
        }
        let e = find_with(Some(Path::new("firefox")), &env, &files(&[])).unwrap_err();
        assert!(e.to_string().contains("--browser firefox"), "{e}");
        let e = find_with(None, &env, &files(&[])).unwrap_err();
        assert!(e.to_string().contains("Firefox"), "{e}");
    }

    #[test]
    fn app_bundles() {
        let exists = files(&["/Apps/Brave Browser.app/Contents/MacOS/Brave Browser"]);
        let env = env_of(&[]);
        assert_eq!(
            find_with(Some(Path::new("/Apps/Brave Browser.app")), &env, &exists).unwrap(),
            Path::new("/Apps/Brave Browser.app/Contents/MacOS/Brave Browser")
        );
        let exists = files(&["/Apps/Firefox Nightly.app/Contents/MacOS/firefox"]);
        let found = find_with(Some(Path::new("/Apps/Firefox Nightly.app")), &env, &exists).unwrap();
        assert_eq!(
            found,
            Path::new("/Apps/Firefox Nightly.app/Contents/MacOS/firefox")
        );
        assert_eq!(Engine::of(&found), Engine::Firefox);
    }

    #[test]
    fn install_paths_then_path() {
        let home = if cfg!(windows) {
            r"C:\Users\me"
        } else {
            "/home/me"
        };
        let env = env_of(&[
            ("HOME", home),
            ("ProgramFiles", r"C:\Program Files"),
            ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
        ]);
        let installed = platform::browser_install_paths(&env);
        assert!(!installed.is_empty());
        // The second well-known path wins over PATH and later ones.
        let second = installed[1].to_string_lossy().into_owned();
        let last = installed.last().unwrap().to_string_lossy().into_owned();
        let path = path_var(&["/usr/bin"]);
        let name = platform::browser_names()[0];
        let on_path = Path::new("/usr/bin").join(name);
        let on_path = on_path.to_string_lossy().into_owned();
        let env = env_of(&[
            ("HOME", home),
            ("ProgramFiles", r"C:\Program Files"),
            ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
            ("PATH", &path),
        ]);
        let exists = files(&[&last, &second, &on_path]);
        assert_eq!(find_with(None, &env, &exists).unwrap(), installed[1]);
        // Nothing installed: PATH.
        let exists = files(&[&on_path]);
        assert_eq!(find_with(None, &env, &exists).unwrap(), Path::new(&on_path));
        let e = find_with(None, &env, &files(&[])).unwrap_err();
        assert!(e.to_string().contains("--browser PATH"), "{e}");
    }

    #[test]
    fn known_install_paths() {
        let env = env_of(&[
            ("HOME", "/Users/me"),
            ("ProgramFiles", r"C:\Program Files"),
            ("ProgramFiles(x86)", r"C:\Program Files (x86)"),
            ("LOCALAPPDATA", r"C:\Users\me\AppData\Local"),
        ]);
        let all: Vec<String> = platform::browser_install_paths(&env)
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect();
        let firefox: Vec<String> = platform::firefox_install_paths(&env)
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect();
        if cfg!(target_os = "macos") {
            assert_eq!(
                firefox[0],
                "/Applications/Firefox.app/Contents/MacOS/firefox"
            );
            assert!(firefox.contains(
                &"/Users/me/Applications/Firefox Nightly.app/Contents/MacOS/firefox".into()
            ));
        } else if cfg!(target_os = "windows") {
            assert_eq!(firefox[0], r"C:\Program Files\Mozilla Firefox\firefox.exe");
            assert!(
                firefox.contains(&r"C:\Users\me\AppData\Local\Mozilla Firefox\firefox.exe".into())
            );
        } else {
            assert_eq!(firefox[0], "/usr/lib/firefox/firefox");
        }
        if cfg!(target_os = "macos") {
            assert_eq!(
                all[0],
                "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
            );
            assert!(all.contains(
                &"/Users/me/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge".into()
            ));
        } else if cfg!(target_os = "windows") {
            assert_eq!(
                all[0],
                r"C:\Program Files\Google\Chrome\Application\chrome.exe"
            );
            assert!(all
                .iter()
                .any(|p| p.ends_with(r"Edge\Application\msedge.exe")));
        } else {
            assert_eq!(all[0], "/opt/google/chrome/chrome");
        }
    }

    #[test]
    fn real_profiles_are_refused() {
        let real = vec![PathBuf::from("/home/me/.config/google-chrome")];
        assert!(check_not_real(Path::new("/home/me/.config/google-chrome"), &real).is_err());
        assert!(
            check_not_real(Path::new("/home/me/.config/google-chrome/Default"), &real).is_err()
        );
        assert!(check_not_real(Path::new("/home/me/.config"), &real).is_err());
        assert!(check_not_real(Path::new("/home/me/tvpipe-profile"), &real).is_ok());
        let env = env_of(&[
            ("HOME", "/Users/me"),
            ("LOCALAPPDATA", r"C:\L"),
            ("APPDATA", r"C:\R"),
        ]);
        let dirs = platform::default_profile_dirs(&env);
        assert!(!dirs.is_empty());
        // Firefox's profiles too.
        let firefox = if cfg!(target_os = "macos") {
            "/Users/me/Library/Application Support/Firefox"
        } else if cfg!(target_os = "windows") {
            r"C:\R\Mozilla\Firefox"
        } else {
            "/Users/me/.mozilla/firefox"
        };
        assert!(dirs.contains(&PathBuf::from(firefox)), "{dirs:?}");
    }

    #[test]
    fn temporary_profiles_are_deleted() {
        let p = Profile::temporary().unwrap();
        let dir = p.dir().to_path_buf();
        assert!(dir.is_dir());
        assert!(dir
            .file_name()
            .unwrap()
            .to_string_lossy()
            .starts_with("tvpipe-browser-"));
        std::fs::write(dir.join("Cookies"), b"x").unwrap();
        std::fs::create_dir(dir.join("Default")).unwrap();
        drop(p);
        assert!(!dir.exists());
        // A persistent one stays.
        let keep = std::env::temp_dir().join(format!("tvpipe-keep-{}", std::process::id()));
        let p = Profile::persistent(&keep).unwrap();
        drop(p);
        assert!(keep.is_dir());
        std::fs::remove_dir_all(&keep).unwrap();
    }

    #[test]
    fn stale_profiles_are_swept() {
        let root = std::env::temp_dir().join(format!("tvpipe-sweep-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir(&root).unwrap();
        let mk = |name: &str, owner: Option<String>| {
            let d = root.join(name);
            std::fs::create_dir(&d).unwrap();
            if let Some(o) = owner {
                std::fs::write(d.join(OWNER_FILE), o).unwrap();
            }
            d
        };
        // Its tvpipe runs.
        let live = Profile::temporary_in(&root).unwrap();
        let owner = std::fs::read_to_string(live.dir().join(OWNER_FILE)).unwrap();
        assert!(
            owner.starts_with(&format!("{} ", std::process::id())),
            "{owner}"
        );
        // Its tvpipe was killed: no beacon, the directory and a
        // DevToolsActivePort of a browser that is gone as well.
        let mut dead = Profile::temporary_in(&root).unwrap();
        dead.beacon = None;
        dead.temporary = false;
        let dead_dir = dead.dir().to_path_buf();
        drop(dead);
        let closed = TcpListener::bind("127.0.0.1:0").unwrap();
        let gone_port = closed.local_addr().unwrap().port();
        drop(closed);
        std::fs::write(
            dead_dir.join("DevToolsActivePort"),
            format!("{gone_port}\n/devtools/browser/x\n"),
        )
        .unwrap();
        // Something else on the beacon's port (it does not say the nonce).
        let other = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = other.local_addr().unwrap().port();
        let squatted = mk(
            &format!("{TEMP_PREFIX}squatted"),
            Some(format!("1 {port} 00ff")),
        );
        let garbage = mk(&format!("{TEMP_PREFIX}garbage"), Some("x".into()));
        // Being made (no owner file yet), and not ours.
        let fresh = mk(&format!("{TEMP_PREFIX}fresh"), None);
        let unrelated = mk("tvpipe-session-1", Some("1 1 1".into()));

        assert_eq!(sweep_in(&root, ORPHAN_AGE), 3);
        for d in [&dead_dir, &squatted, &garbage] {
            assert!(!d.exists(), "{} was kept", d.display());
        }
        for d in [live.dir(), &fresh, &unrelated] {
            assert!(d.exists(), "{} was removed", d.display());
        }
        // An old directory without an owner file goes too.
        assert_eq!(sweep_in(&root, Duration::ZERO), 1);
        assert!(!fresh.exists() && live.dir().exists());
        drop(other);
        let live_dir = live.dir().to_path_buf();
        drop(live);
        assert!(!live_dir.exists());
        std::fs::remove_dir_all(&root).unwrap();
    }

    /// A browser left running by a killed tvpipe is quit, its profile
    /// removed (opt-in: TVPIPE_TEST_CHROME=/path/to/chrome).
    #[test]
    #[ignore]
    fn chrome_left_by_a_killed_tvpipe_is_swept() {
        let Ok(bin) = std::env::var("TVPIPE_TEST_CHROME") else {
            eprintln!("TVPIPE_TEST_CHROME not set");
            return;
        };
        left_by_a_killed_tvpipe_is_swept(&bin);
    }

    /// The same with Firefox (opt-in: TVPIPE_TEST_FIREFOX=/path/to/firefox).
    #[test]
    #[ignore]
    fn firefox_left_by_a_killed_tvpipe_is_swept() {
        let Ok(bin) = std::env::var("TVPIPE_TEST_FIREFOX") else {
            eprintln!("TVPIPE_TEST_FIREFOX not set");
            return;
        };
        left_by_a_killed_tvpipe_is_swept(&bin);
    }

    fn left_by_a_killed_tvpipe_is_swept(bin: &str) {
        let root = std::env::temp_dir().join(format!(
            "tvpipe-sweep-{}-{}",
            if Engine::of(Path::new(bin)) == Engine::Firefox {
                "firefox"
            } else {
                "chrome"
            },
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir(&root).unwrap();
        let mut profile = Profile::temporary_in(&root).unwrap();
        let opts = LaunchOptions {
            bin: bin.into(),
            viewport: (640, 360),
            visible: false,
            screen: None,
        };
        let mut browser = Browser::launch(&opts, &profile).unwrap();
        // tvpipe dies: nobody closes the browser or deletes the profile.
        let mut child = browser.child.take().unwrap();
        drop(browser);
        profile.beacon = None;
        profile.temporary = false;
        let dir = profile.dir().to_path_buf();
        drop(profile);
        assert!(
            child.try_wait().unwrap().is_none(),
            "the browser should still run"
        );

        // Without an owner file (a tvpipe from before the beacons) a
        // profile with a running browser is left alone.
        let owner = std::fs::read(dir.join(OWNER_FILE)).unwrap();
        std::fs::remove_file(dir.join(OWNER_FILE)).unwrap();
        assert_eq!(sweep_in(&root, Duration::ZERO), 0);
        assert!(child.try_wait().unwrap().is_none());
        std::fs::write(dir.join(OWNER_FILE), owner).unwrap();

        assert_eq!(sweep_in(&root, ORPHAN_AGE), 1);
        assert!(!dir.exists());
        let status = child.try_wait().unwrap();
        assert!(status.is_some(), "the browser still runs");
        if !cfg!(windows) {
            let out = Command::new("ps")
                .args(["-A", "-o", "command="])
                .output()
                .unwrap();
            let needle = dir.to_string_lossy().into_owned();
            let left: Vec<String> = String::from_utf8_lossy(&out.stdout)
                .lines()
                .filter(|l| l.contains(&needle))
                .map(str::to_owned)
                .collect();
            assert!(left.is_empty(), "browser processes left: {left:#?}");
        }
        std::fs::remove_dir_all(&root).unwrap();
    }

    #[test]
    fn command_line() {
        let o = LaunchOptions {
            bin: "chrome".into(),
            viewport: (1280, 720),
            visible: false,
            screen: None,
        };
        let a: Vec<String> = args(&o, Path::new("/tmp/p"))
            .into_iter()
            .map(|s| s.into_string().unwrap())
            .collect();
        for want in [
            "--headless=new",
            "--screen-info={0,0 1280x720}",
            "--user-data-dir=/tmp/p",
            "--remote-debugging-port=0",
            "--auto-accept-this-tab-capture",
            "--autoplay-policy=no-user-gesture-required",
            "--window-size=1280,720",
            "--force-device-scale-factor=1",
        ] {
            assert!(a.iter().any(|x| x == want), "{want} missing: {a:?}");
        }
        assert_eq!(a.last().unwrap(), "about:blank");
        let visible: Vec<OsString> = args(
            &LaunchOptions {
                visible: true,
                ..o.clone()
            },
            Path::new("/tmp/p"),
        );
        assert!(!visible
            .iter()
            .any(|x| x.to_string_lossy().starts_with("--headless")
                || x.to_string_lossy().starts_with("--screen-info")));

        // Firefox: its own flags, the profile as a separate argument.
        let ff = LaunchOptions {
            bin: "/opt/firefox/firefox".into(),
            ..o
        };
        assert_eq!(ff.engine(), Engine::Firefox);
        let a: Vec<String> = args(&ff, Path::new("/tmp/my p"))
            .into_iter()
            .map(|s| s.into_string().unwrap())
            .collect();
        assert_eq!(
            a,
            [
                "--headless",
                "--profile",
                "/tmp/my p",
                "--no-remote",
                "--new-instance",
                "--remote-debugging-port=0",
                "--marionette",
                "--window-size=1280,720",
                "about:blank"
            ]
        );
    }

    #[test]
    fn firefox_preferences() {
        let js = firefox_user_js();
        for want in [
            "user_pref(\"media.navigator.permission.disabled\", true);",
            "user_pref(\"media.getusermedia.browser.enabled\", true);",
            "user_pref(\"media.getusermedia.audio.capture.enabled\", true);",
            "user_pref(\"media.autoplay.default\", 0);",
            "user_pref(\"media.volume_scale\", \"0.0\");",
        ] {
            assert!(js.lines().any(|l| l == want), "{want} missing:\n{js}");
        }
        // Every line a comment or a pref with a JSON value.
        for l in js.lines().skip(1) {
            let inner = l
                .strip_prefix("user_pref(")
                .and_then(|r| r.strip_suffix(");"))
                .unwrap_or_else(|| panic!("{l}"));
            let (k, v) = inner.split_once(", ").unwrap();
            assert!(Value::parse(k).unwrap().as_str().is_some(), "{l}");
            Value::parse(v).unwrap_or_else(|e| panic!("{l}: {e}"));
        }
    }

    #[test]
    fn active_port_file() {
        assert_eq!(
            parse_active_port("53211\n/devtools/browser/0b5f-11\n"),
            Some((53211, "/devtools/browser/0b5f-11".into()))
        );
        assert_eq!(parse_active_port("53211\n"), None);
        assert_eq!(parse_active_port("0\n/devtools/browser/x"), None);
        assert_eq!(parse_active_port("x\n/devtools/browser/x"), None);
        assert_eq!(parse_active_port("1\n/etc/passwd"), None);
        assert_eq!(parse_active_port(""), None);
    }
}