tvpipe 0.3.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
//! The state of one playshare run: the API sockets, the relay's client
//! connections and its host, the launcher's selection, discovery, pairing
//! and the cast (docs/playshare-design.md §5, §6).
//!
//! Locks: `Hub::st` is taken briefly and never while waiting on a socket;
//! outboxes have locks of their own, taken after `st` or alone.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock};
use std::time::{Duration, Instant};

use crate::codec::json::Value;
use crate::error::{Error, Result};
use crate::events::{Events, Progress};
use crate::net::tunnel::PeerLookup;
use crate::net::websocket::Message;
use crate::util::stop::Stop;

use super::backend::{Backend, Cast, Discover, Pair};
use super::bundle::Bundle;
use super::conn::{self, Next, Out, WindowCounter};
use super::resolution::{Picture, Resolution};

/// Relay frame ops (§6.2).
pub const OP_TEXT: u8 = 1;
pub const OP_BINARY: u8 = 2;

/// A client's backlog that is reported as `busy`.
pub const BUSY_MARK: usize = 64 * 1024;
/// A client's backlog that closes it (4013, it reconnects).
pub const CLIENT_LIMIT: usize = 1 << 20;
/// The first message from a client must come within this.
pub const FIRST_MESSAGE: Duration = Duration::from_secs(10);
/// Upgrades per address and minute.
pub const UPGRADES_PER_MINUTE: usize = 60;
/// The API socket's largest message (the host sends to many clients).
pub const API_MAX_MESSAGE: usize = 16 << 20;
/// How long the host gets to say goodbye at the end.
pub const CLOSING_GRACE: Duration = Duration::from_secs(1);

/// The close code that tells clients the game ended (final for them).
pub const CLOSE_ENDED: u16 = 4011;
/// The close code for clients when the host went away (they reconnect).
pub const CLOSE_RESTART: u16 = 1012;

/// Where a relayed connection came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Via {
    /// The public listener: the tunnel, or loopback for tests.
    Public,
    /// The LAN listener.
    Lan,
    /// The local listener: the TV page, previews in the host window.
    Local,
}

impl Via {
    pub fn as_str(self) -> &'static str {
        match self {
            Via::Public => "public",
            Via::Lan => "lan",
            Via::Local => "local",
        }
    }
}

/// The listeners' addresses, once bound.
#[derive(Debug, Clone, Copy)]
pub struct Ports {
    pub local: u16,
    pub public: u16,
    pub lan: Option<SocketAddr>,
}

/// The tunnel as the API reports it.
#[derive(Debug, Clone, Default)]
pub struct TunnelInfo {
    /// `off`, `starting`, `up`, `failed`.
    pub state: &'static str,
    pub provider: Option<String>,
    pub host: Option<String>,
    pub error: Option<String>,
}

struct Client {
    out: Out,
}

pub(super) struct Api {
    out: Out,
    watching: bool,
}

pub(super) struct St {
    next_conn: u32,
    next_api: u64,
    clients: HashMap<u32, Client>,
    pub(super) apis: HashMap<u64, Api>,
    host: Option<u64>,
    selection: Vec<String>,
    /// The chosen resolution (the launcher's or the cast picker's).
    resolution: Resolution,
    upgrades: WindowCounter,
    discovery: Option<Box<dyn Discover>>,
    devices: Value,
    pairs: HashMap<String, (Box<dyn Pair>, Value)>,
    cast: Option<(Box<dyn Cast>, Value)>,
    /// When the last API socket went away (none open), or when the run
    /// started if none came yet.
    apis_gone_since: Option<Instant>,
    seen_api: bool,
    closing: bool,
    /// The short link the front end was told about last.
    short_shown: Option<String>,
}

pub struct Hub {
    pub bundle: Bundle,
    pub token: String,
    pub ports: OnceLock<Ports>,
    pub tunnel: RwLock<TunnelInfo>,
    pub peers: RwLock<Option<PeerLookup>>,
    pub stop: Stop,
    pub version: &'static str,
    pub(super) backend: Box<dyn Backend>,
    st: Mutex<St>,
    pub(super) surfaces: Mutex<super::surface::Surfaces>,
    /// The run's progress for people (the CLI's terminal UI), set once.
    pub events: OnceLock<Events>,
    /// Short join links (`shortlink`), set once; unset: none.
    pub shortlinks: OnceLock<Arc<super::shortlink::ShortLinks>>,
}

/// `{"t":"event","type":…,"data":…}`.
fn event(kind: &str, data: Value) -> String {
    Value::object()
        .with("t", "event")
        .with("type", kind)
        .with("data", data)
        .to_json()
}

fn reply_ok(n: &Value, value: Value) -> String {
    Value::object()
        .with("t", "reply")
        .with("n", n.clone())
        .with("ok", true)
        .with("value", value)
        .to_json()
}

fn reply_err(n: &Value, code: &str, message: &str) -> String {
    Value::object()
        .with("t", "reply")
        .with("n", n.clone())
        .with("ok", false)
        .with(
            "error",
            Value::object().with("code", code).with("message", message),
        )
        .to_json()
}

/// A relay data frame: `op | conn (u32be) | payload`.
pub fn frame(op: u8, conn: u32, payload: &[u8]) -> Vec<u8> {
    let mut f = Vec::with_capacity(5 + payload.len());
    f.push(op);
    f.extend_from_slice(&conn.to_be_bytes());
    f.extend_from_slice(payload);
    f
}

/// A `resolution` parameter.
fn parse_resolution(v: &Value) -> Result<Resolution> {
    v.as_str().and_then(Resolution::parse).ok_or_else(|| {
        Error::usage("resolution is auto, 720p, 1080p or 2160p").with_code("bad-resolution")
    })
}

/// The pseudo-receiver for a browser tab on this computer.
pub fn browser_device() -> Value {
    Value::object()
        .with("name", "browser")
        .with("kind", "browser")
        .with("title", "A browser tab on this computer")
}

impl Hub {
    pub fn new(bundle: Bundle, token: String, backend: Box<dyn Backend>, stop: Stop) -> Arc<Hub> {
        Arc::new(Hub {
            bundle,
            token,
            ports: OnceLock::new(),
            tunnel: RwLock::new(TunnelInfo {
                state: "off",
                ..TunnelInfo::default()
            }),
            peers: RwLock::new(None),
            stop,
            version: env!("CARGO_PKG_VERSION"),
            backend,
            surfaces: Mutex::default(),
            events: OnceLock::new(),
            shortlinks: OnceLock::new(),
            st: Mutex::new(St {
                short_shown: None,
                next_conn: 0,
                next_api: 0,
                clients: HashMap::new(),
                apis: HashMap::new(),
                host: None,
                selection: Vec::new(),
                resolution: Resolution::Auto,
                upgrades: WindowCounter::new(UPGRADES_PER_MINUTE, Duration::from_secs(60)),
                discovery: None,
                devices: Value::array(Vec::<Value>::new()),
                pairs: HashMap::new(),
                cast: None,
                apis_gone_since: Some(Instant::now()),
                seen_api: false,
                closing: false,
            }),
        })
    }

    pub(super) fn lock(&self) -> MutexGuard<'_, St> {
        self.st.lock().unwrap_or_else(|e| e.into_inner())
    }

    fn ports(&self) -> Ports {
        self.ports.get().copied().unwrap_or(Ports {
            local: 0,
            public: 0,
            lan: None,
        })
    }

    /// The local origin (`http://127.0.0.1:L`).
    pub fn local_origin(&self) -> String {
        format!("http://127.0.0.1:{}", self.ports().local)
    }

    /// What phones open: `(base URL, mode)`.
    pub fn phone_base(&self) -> (String, &'static str) {
        let t = self.tunnel.read().unwrap_or_else(|e| e.into_inner());
        if let (Some(host), "up") = (&t.host, t.state) {
            return (format!("https://{host}/"), "tunnel");
        }
        let p = self.ports();
        if let Some(lan) = p.lan {
            return (format!("http://{lan}/"), "lan");
        }
        (format!("http://127.0.0.1:{}/", p.public), "local")
    }

    /// The most connections the relay takes at once.
    pub fn max_clients(&self) -> usize {
        (2 * self.bundle.manifest.max_players as usize + 16).max(64)
    }

    // -----------------------------------------------------------------
    // Events

    fn broadcast(&self, st: &St, text: &str) {
        for a in st.apis.values() {
            a.out.text(text.to_owned());
        }
    }

    /// A progress event for the program's front end.
    pub fn progress(&self, p: Progress) {
        if let Some(e) = self.events.get() {
            e.progress(p);
        }
    }

    /// Sends an event to every API socket.
    pub fn event(&self, kind: &str, data: Value) {
        let text = event(kind, data);
        let st = self.lock();
        self.broadcast(&st, &text);
    }

    pub fn tunnel_value(&self) -> Value {
        let t = self.tunnel.read().unwrap_or_else(|e| e.into_inner());
        Value::object()
            .with("state", t.state)
            .with_opt("provider", t.provider.as_deref())
            .with_opt("url", t.host.as_ref().map(|h| format!("https://{h}/")))
            .with_opt("error", t.error.as_deref())
    }

    /// The tunnel changed: tell the API sockets.
    pub fn tunnel_changed(&self) {
        self.event("tunnel", self.tunnel_value());
    }

    // -----------------------------------------------------------------
    // The relay's clients

    /// Whether a new client may connect from `addr` (`Err`: the HTTP
    /// status and reason).
    pub fn admit(&self, addr: &str) -> std::result::Result<(), (u16, &'static str)> {
        let mut st = self.lock();
        if st.closing || st.host.is_none() {
            return Err((503, "Service Unavailable"));
        }
        if st.clients.len() >= self.max_clients() {
            return Err((503, "Service Unavailable"));
        }
        if !st.upgrades.hit(addr, Instant::now()) {
            return Err((429, "Too Many Requests"));
        }
        Ok(())
    }

    /// Runs an upgraded client socket until it ends.
    pub fn run_client(
        self: &Arc<Hub>,
        tcp: std::net::TcpStream,
        leftover: Vec<u8>,
        via: Via,
        addr: String,
        query: String,
        agent: String,
    ) {
        let limits = self.bundle.manifest.limits;
        let id = Arc::new(OnceLock::<u32>::new());
        let hub = self.clone();
        let mark_id = id.clone();
        let mark: conn::MarkFn = Box::new(move |busy| {
            if let Some(&conn) = mark_id.get() {
                let st = hub.lock();
                if let Some(h) = st.host.and_then(|h| st.apis.get(&h)) {
                    let t = if busy { "busy" } else { "drain" };
                    h.out
                        .text(Value::object().with("t", t).with("conn", conn).to_json());
                }
            }
        });
        let opts = conn::Options {
            name: "relay",
            max_message: limits.message as usize,
            first_message: Some(FIRST_MESSAGE),
            mark: Some((BUSY_MARK, mark)),
            limit: Some((CLIENT_LIMIT, 4013, "slow")),
        };
        let mut bucket = conn::Bucket::new(limits.rate, limits.burst);
        let hub = self.clone();
        let registered = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let reg = registered.clone();
        let ended = conn::run(
            tcp,
            leftover,
            opts,
            |out| {
                let mut st = hub.lock();
                let Some(host) = st.host.filter(|_| !st.closing) else {
                    out.close(CLOSE_RESTART, "no host");
                    return;
                };
                st.next_conn += 1;
                let conn = st.next_conn;
                let _ = id.set(conn);
                st.clients.insert(conn, Client { out: out.clone() });
                reg.store(true, std::sync::atomic::Ordering::SeqCst);
                let open = Value::object()
                    .with("t", "open")
                    .with("conn", conn)
                    .with("via", via.as_str())
                    .with("addr", addr.as_str())
                    .with("query", query.as_str())
                    .with("agent", agent.as_str())
                    .to_json();
                if let Some(h) = st.apis.get(&host) {
                    h.out.text(open);
                }
                debug!("playshare: client {conn} from {addr} ({})", via.as_str());
            },
            |msg| {
                let Some(&conn) = id.get() else {
                    return Next::Close(CLOSE_RESTART, "no host".into());
                };
                if !bucket.take() {
                    info!("playshare: client {conn} sends too fast; closed");
                    return Next::Close(4008, "rate-limited".into());
                }
                let (op, payload) = match msg {
                    Message::Text(t) => (OP_TEXT, t.into_bytes()),
                    Message::Binary(b) => (OP_BINARY, b),
                    Message::Close(_) => return Next::Continue,
                };
                let st = hub.lock();
                match st.host.and_then(|h| st.apis.get(&h)) {
                    Some(h) => {
                        h.out.binary(frame(op, conn, &payload));
                        Next::Continue
                    }
                    None => Next::Close(CLOSE_RESTART, "no host".into()),
                }
            },
        );
        if !registered.load(std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        let Some(&conn) = id.get() else { return };
        let mut st = self.lock();
        st.clients.remove(&conn);
        if let Some(h) = st.host.and_then(|h| st.apis.get(&h)) {
            h.out.text(
                Value::object()
                    .with("t", "close")
                    .with("conn", conn)
                    .with("code", u64::from(ended.code))
                    .with("reason", ended.reason.as_str())
                    .to_json(),
            );
        }
        debug!("playshare: client {conn} closed ({})", ended.code);
    }

    fn close_clients(st: &mut St, code: u16, reason: &str) {
        for c in st.clients.values() {
            c.out.close(code, reason);
        }
    }

    /// Clients still connected.
    pub fn client_count(&self) -> usize {
        self.lock().clients.len()
    }

    // -----------------------------------------------------------------
    // API sockets

    /// Runs an upgraded API socket until it ends.
    pub fn run_api(self: &Arc<Hub>, tcp: std::net::TcpStream, leftover: Vec<u8>) {
        let id = {
            let mut st = self.lock();
            st.next_api += 1;
            st.next_api
        };
        let opts = conn::Options {
            name: "playshare-api",
            max_message: API_MAX_MESSAGE,
            first_message: None,
            mark: None,
            limit: None,
        };
        let hub = self.clone();
        let my_out: std::cell::OnceCell<Out> = std::cell::OnceCell::new();
        conn::run(
            tcp,
            leftover,
            opts,
            |out| {
                let _ = my_out.set(out.clone());
                let mut st = hub.lock();
                st.apis.insert(
                    id,
                    Api {
                        out: out.clone(),
                        watching: false,
                    },
                );
                st.seen_api = true;
                st.apis_gone_since = None;
                if st.closing {
                    out.text(event("closing", Value::Null));
                }
            },
            |msg| {
                match msg {
                    Message::Text(t) => hub.on_api_text(id, my_out.get(), &t),
                    Message::Binary(b) => hub.on_host_data(id, &b),
                    Message::Close(_) => {}
                }
                Next::Continue
            },
        );
        let mut st = self.lock();
        st.apis.remove(&id);
        if st.apis.is_empty() {
            st.apis_gone_since = Some(Instant::now());
        }
        if st.host == Some(id) {
            st.host = None;
            info!("playshare: the host page went away; phones reconnect when it is back");
            Hub::close_clients(&mut st, CLOSE_RESTART, "host restart");
        }
    }

    /// Data from the host for a client.
    fn on_host_data(&self, api: u64, data: &[u8]) {
        if data.len() < 5 {
            return;
        }
        let op = data[0];
        let conn = u32::from_be_bytes([data[1], data[2], data[3], data[4]]);
        // Pushing may report `busy`, which takes the lock: not under it.
        let out = {
            let st = self.lock();
            if st.host != Some(api) {
                return;
            }
            let Some(c) = st.clients.get(&conn) else {
                return;
            };
            c.out.clone()
        };
        let payload = &data[5..];
        match op {
            OP_TEXT => {
                if let Ok(t) = std::str::from_utf8(payload) {
                    out.text(t.to_owned());
                }
            }
            OP_BINARY => {
                out.binary(payload.to_vec());
            }
            _ => {}
        }
    }

    fn on_api_text(self: &Arc<Hub>, api: u64, out: Option<&Out>, text: &str) {
        let Some(out) = out else { return };
        let Ok(msg) = Value::parse(text) else {
            debug!("playshare: API message that is not JSON");
            return;
        };
        match msg.get("t").and_then(Value::as_str) {
            Some("call") => {
                let n = msg.get("n").cloned().unwrap_or(Value::Null);
                let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
                let params = msg.get("params").cloned().unwrap_or_else(Value::object);
                if matches!(method, "cast.start" | "surface.open" | "shortlink") {
                    // Starting a cast takes seconds, a short link a
                    // request to the service: not on the reader.
                    let (hub, out, method) = (self.clone(), out.clone(), method.to_owned());
                    let _ = std::thread::Builder::new()
                        .name(format!("playshare-{method}"))
                        .spawn(move || {
                            let r = hub.call(api, &method, &params);
                            out.text(match r {
                                Ok(v) => reply_ok(&n, v),
                                Err(e) => reply_err(&n, e.code().unwrap_or("failed"), e.message()),
                            });
                        });
                    return;
                }
                let r = self.call(api, method, &params);
                out.text(match r {
                    Ok(v) => reply_ok(&n, v),
                    Err(e) => reply_err(&n, e.code().unwrap_or("failed"), e.message()),
                });
            }
            Some("close") => {
                let st = self.lock();
                if st.host != Some(api) {
                    return;
                }
                let conn = msg.get("conn").and_then(Value::as_u64).unwrap_or(0);
                let code = msg
                    .get("code")
                    .and_then(Value::as_u64)
                    .and_then(|c| u16::try_from(c).ok())
                    .filter(|c| *c == 1000 || (3000..=4999).contains(c))
                    .unwrap_or(1000);
                let reason: String = msg
                    .get("reason")
                    .and_then(Value::as_str)
                    .unwrap_or("")
                    .chars()
                    .take(60)
                    .collect();
                if let Some(c) = u32::try_from(conn).ok().and_then(|c| st.clients.get(&c)) {
                    c.out.close(code, &reason);
                }
            }
            _ => {}
        }
    }

    /// One API call.
    pub fn call(self: &Arc<Hub>, api: u64, method: &str, params: &Value) -> Result<Value> {
        let unknown = || Error::usage(format!("no method {method:?}")).with_code("unknown-method");
        match method {
            "info" => Ok(self.info()),
            "devices.watch" => {
                let on = params.get("on").and_then(Value::as_bool).unwrap_or(true);
                let mut st = self.lock();
                if let Some(a) = st.apis.get_mut(&api) {
                    a.watching = on;
                }
                Ok(st.devices.clone())
            }
            "select" => {
                let list = params
                    .get("devices")
                    .and_then(Value::as_array)
                    .ok_or_else(|| Error::usage("select: devices is a list of names"))?;
                let names: Vec<String> = list
                    .iter()
                    .filter_map(Value::as_str)
                    .filter(|s| !s.is_empty() && s.len() <= 200)
                    .take(16)
                    .map(str::to_owned)
                    .collect();
                let resolution = match params.get("resolution") {
                    None | Some(Value::Null) => None,
                    Some(r) => Some(parse_resolution(r)?),
                };
                let mut st = self.lock();
                st.selection = names;
                if let Some(r) = resolution {
                    st.resolution = r;
                }
                Ok(self.selection_value(&st))
            }
            "selection" => Ok(self.selection_value(&self.lock())),
            "pair.start" => {
                let device = params
                    .get("device")
                    .and_then(Value::as_str)
                    .ok_or_else(|| Error::usage("pair.start: device"))?;
                let job = self.backend.pair(device)?;
                let mut st = self.lock();
                if let Some((old, _)) = st.pairs.remove(device) {
                    old.cancel();
                }
                st.pairs.insert(device.to_owned(), (job, Value::Null));
                Ok(Value::object())
            }
            "pair.pin" => {
                let device = params.get("device").and_then(Value::as_str).unwrap_or("");
                let pin = params
                    .get("pin")
                    .and_then(Value::as_str)
                    .ok_or_else(|| Error::usage("pair.pin: pin"))?;
                let st = self.lock();
                let (job, _) = st
                    .pairs
                    .get(device)
                    .ok_or_else(|| Error::usage(format!("no pairing with {device:?}")))?;
                job.submit(pin)?;
                Ok(Value::object())
            }
            "pair.cancel" => {
                let device = params.get("device").and_then(Value::as_str).unwrap_or("");
                if let Some((job, _)) = self.lock().pairs.remove(device) {
                    job.cancel();
                }
                Ok(Value::object())
            }
            "cast.start" => self.cast_start(params),
            "cast.stop" => {
                let old = self.lock().cast.take();
                if let Some((c, _)) = old {
                    c.stop();
                }
                self.event("cast", Value::object().with("state", "stopped"));
                self.progress(Progress::CastStopped);
                Ok(Value::object())
            }
            "qr" => {
                let text = params
                    .get("text")
                    .and_then(Value::as_str)
                    .ok_or_else(|| Error::usage("qr: text"))?;
                let qr = crate::util::qr::encode(text.as_bytes(), crate::util::qr::MAX_VERSION)
                    .ok_or_else(|| Error::usage("qr: the text does not fit a QR code"))?;
                let rows = qr.rows();
                Ok(Value::object().with("size", rows.len()).with("rows", rows))
            }
            "relay.attach" => {
                let mut st = self.lock();
                if st.closing {
                    return Err(Error::closed("playshare is ending").with_code("closing"));
                }
                if let Some(old) = st.host.filter(|h| *h != api) {
                    if let Some(a) = st.apis.get(&old) {
                        a.out.text(event("detached", Value::Null));
                        a.out.close(1000, "replaced");
                    }
                    Hub::close_clients(&mut st, CLOSE_RESTART, "host restart");
                    info!("playshare: a new host page took over");
                }
                st.host = Some(api);
                drop(st);
                let (phone, mode) = self.phone_base();
                Ok(Value::object()
                    .with("public", phone)
                    .with("mode", mode)
                    .with("local", self.local_origin()))
            }
            "surface.open" => {
                let selection = self.lock().selection.clone();
                self.surface_open(params, selection)
            }
            "surface.close" => {
                let id = params
                    .get("id")
                    .and_then(Value::as_u32)
                    .ok_or_else(|| Error::usage("surface.close: id"))?;
                self.surface_close(id)
            }
            "shortlink" => self.shortlink(params),
            "quit" => {
                info!("playshare: the page asked to quit");
                self.stop.request();
                Ok(Value::object())
            }
            _ => Err(unknown()),
        }
    }

    /// `shortlink {url, code}`: a short link for the tunnel's join link
    /// (docs/short-links.md), `{url, code}`.
    fn shortlink(&self, params: &Value) -> Result<Value> {
        let url = params
            .get("url")
            .and_then(Value::as_str)
            .ok_or_else(|| Error::usage("shortlink: url (the join link)"))?;
        let code = params.get("code").and_then(Value::as_str);
        let unavailable = |m: &'static str| Error::unsupported(m).with_code("unavailable");
        let host =
            {
                let t = self.tunnel.read().unwrap_or_else(|e| e.into_inner());
                match (&t.host, t.state) {
                    (Some(h), "up") => h.clone(),
                    _ => return Err(unavailable(
                        "short links are only for the tunnel's join link, and there is no tunnel",
                    )),
                }
            };
        let ours = url
            .strip_prefix("https://")
            .and_then(|r| r.strip_prefix(host.as_str()))
            .is_some_and(|r| r.starts_with('/'));
        if !ours {
            return Err(Error::usage(format!(
                "shortlink: only for the tunnel's join link (https://{host}/…)"
            ))
            .with_code("bad-url"));
        }
        let links = self
            .shortlinks
            .get()
            .filter(|l| l.enabled())
            .ok_or_else(|| unavailable("short links are off"))?;
        let (short, code) = links.register(url, code).inspect_err(|e| {
            // The terminal shows only the short link: this one instead.
            if self.lock().short_shown.is_none() {
                warn!(
                    "playshare: no short link ({e}); phones join at https://{host}/ (the QR code)"
                );
            }
        })?;
        let news = {
            let mut st = self.lock();
            let news = st.short_shown.as_deref() != Some(short.as_str());
            st.short_shown = Some(short.clone());
            news
        };
        if news {
            self.progress(Progress::ShortLink { url: short.clone() });
        }
        Ok(Value::object().with("url", short).with("code", code))
    }

    /// Whether a host page attached the relay (`tvpipe game check --smoke`).
    pub fn host_attached(&self) -> bool {
        self.lock().host.is_some()
    }

    pub fn info(&self) -> Value {
        let (phone, mode) = self.phone_base();
        let p = self.ports();
        self.bundle
            .manifest
            .to_value()
            .with(
                "phone",
                Value::object()
                    .with("url", phone)
                    .with("mode", mode)
                    .with_opt("lan", p.lan.map(|l| format!("http://{l}/"))),
            )
            .with("tunnel", self.tunnel_value())
            .with("local", self.local_origin())
            .with("version", self.version)
            .with("resolutions", self.resolutions())
    }

    /// The resolution until someone chooses one (`--resolution`).
    pub fn set_resolution(&self, r: Resolution) {
        self.lock().resolution = r;
    }

    /// The resolutions people may choose (none: `tv.resolution` fixed).
    fn resolutions(&self) -> Value {
        if self.bundle.manifest.tv_fixed {
            return Value::array(Vec::<Value>::new());
        }
        Value::array(Resolution::ALL.iter().map(|r| r.as_str()))
    }

    /// `select`'s and `selection`'s answer.
    fn selection_value(&self, st: &St) -> Value {
        Value::object().with("devices", st.selection.clone()).with(
            "resolution",
            if self.bundle.manifest.tv_fixed {
                Value::Null
            } else {
                Value::from(st.resolution.as_str())
            },
        )
    }

    fn cast_start(self: &Arc<Hub>, params: &Value) -> Result<Value> {
        let page = params
            .get("page")
            .and_then(Value::as_str)
            .ok_or_else(|| Error::usage("cast.start: page (a path of this game)"))?;
        if !page.starts_with('/')
            || page.starts_with("//")
            || page.contains('\\')
            || page.len() > 4096
        {
            return Err(Error::usage(
                "cast.start: page must be a path on the local origin (/tv.html#…)",
            ));
        }
        let to: Vec<String> = match params.get("to").and_then(Value::as_array) {
            Some(list) => list
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_owned)
                .collect(),
            None => self.lock().selection.clone(),
        };
        if to.is_empty() {
            return Err(Error::usage("no receivers chosen").with_code("no-receivers"));
        }
        let resolution = match params.get("resolution") {
            None | Some(Value::Null) => self.lock().resolution,
            Some(r) => parse_resolution(r)?,
        };
        let manifest = &self.bundle.manifest;
        let picture = Picture {
            layout: manifest.tv_size,
            resolution: (!manifest.tv_fixed).then_some(resolution),
        };
        let url = format!("{}{page}", self.local_origin());
        let old = self.lock().cast.take();
        if let Some((c, _)) = old {
            c.stop();
        }
        self.event(
            "cast",
            Value::object()
                .with("state", "starting")
                .with("to", to.clone())
                .with_opt("resolution", picture.resolution.map(Resolution::as_str)),
        );
        info!("playshare: casting to {}", to.join(", "));
        self.progress(Progress::Casting(to.clone()));
        match self.backend.cast(&url, &to, picture) {
            Ok(mut job) => {
                if self.stop.requested() {
                    job.stop();
                    return Err(Error::closed("playshare is ending"));
                }
                let status = job.status();
                self.lock().cast = Some((job, Value::Null));
                Ok(status)
            }
            Err(e) => {
                warn!("playshare: cast: {e}");
                self.progress(Progress::CastFailed(e.message().to_owned()));
                self.event(
                    "cast",
                    Value::object()
                        .with("state", "failed")
                        .with("error", e.message()),
                );
                Err(e)
            }
        }
    }

    // -----------------------------------------------------------------
    // Background work

    /// Discovery, pairing and cast progress: called every ~200 ms.
    pub fn tick(&self) {
        let mut events: Vec<String> = Vec::new();
        let mut st = self.lock();
        let watching = st.apis.values().any(|a| a.watching);
        if watching && st.discovery.is_none() {
            match self.backend.discover() {
                Ok(d) => st.discovery = Some(d),
                Err(e) => warn!("playshare: discovery: {e}"),
            }
        } else if !watching && st.discovery.is_some() {
            st.discovery = None;
        }
        if let Some(d) = &st.discovery {
            let mut list = vec![browser_device()];
            list.extend(d.devices());
            let list = Value::array(list);
            if list != st.devices {
                st.devices = list.clone();
                events.push(event("devices", list));
            }
        }
        let mut done = Vec::new();
        for (device, (job, last)) in st.pairs.iter_mut() {
            let v = job.state().with("device", device.as_str());
            if v != *last {
                *last = v.clone();
                let state = v.get("state").and_then(Value::as_str).unwrap_or("");
                if state == "done" || state == "failed" {
                    done.push(device.clone());
                }
                events.push(event("pair", v));
            }
        }
        for d in done {
            st.pairs.remove(&d);
        }
        let mut progress = None;
        if let Some((job, last)) = st.cast.as_mut() {
            let v = job.status();
            if v != *last {
                let was = last.get("state").and_then(Value::as_str).map(str::to_owned);
                let state = v.get("state").and_then(Value::as_str).unwrap_or("");
                if was.as_deref() != Some(state) {
                    progress = match state {
                        "failed" => Some(Progress::CastFailed(
                            v.get("error")
                                .and_then(Value::as_str)
                                .unwrap_or("the cast failed")
                                .to_owned(),
                        )),
                        "stopped" => Some(Progress::CastStopped),
                        _ => None,
                    };
                }
                *last = v.clone();
                events.push(event("cast", v));
            }
        }
        for e in &events {
            self.broadcast(&st, e);
        }
        drop(st);
        if let Some(p) = progress {
            self.progress(p);
        }
        self.surfaces_tick();
    }

    /// With no window of our own: no API socket for this long ends the run.
    pub fn apis_gone_for(&self) -> Option<Duration> {
        let st = self.lock();
        if !st.seen_api {
            return None;
        }
        st.apis_gone_since.map(|t| t.elapsed())
    }

    /// The end (§10): `closing` to the pages, a second for the host's
    /// goodbyes, then clients closed with 4011 and the cast stopped.
    pub fn shutdown(&self) {
        {
            let mut st = self.lock();
            if st.closing {
                return;
            }
            st.closing = true;
            let has_host = st.host.is_some();
            let text = event("closing", Value::Null);
            self.broadcast(&st, &text);
            drop(st);
            if has_host {
                let until = Instant::now() + CLOSING_GRACE;
                while Instant::now() < until && self.client_count() > 0 {
                    std::thread::sleep(Duration::from_millis(20));
                }
            }
        }
        let (cast, pairs) = {
            let mut st = self.lock();
            Hub::close_clients(&mut st, CLOSE_ENDED, "closed");
            st.discovery = None;
            (st.cast.take(), std::mem::take(&mut st.pairs))
        };
        for (_, (p, _)) in pairs {
            p.cancel();
        }
        if let Some((c, _)) = cast {
            info!("playshare: stopping the cast");
            c.stop();
        }
        self.surfaces_stop_all();
        let st = self.lock();
        for a in st.apis.values() {
            a.out.close(1001, "ended");
        }
        drop(st);
        // Let the close frames go out.
        let until = Instant::now() + Duration::from_millis(500);
        while Instant::now() < until && self.client_count() > 0 {
            std::thread::sleep(Duration::from_millis(20));
        }
    }
}