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
//! `tvpipe game play`: web games served by tvpipe
//! (docs/playshare-design.md). A bundle (a folder or a zip with
//! `tvpipe.json`) is served on two listeners; the game's host page runs
//! in a window of tvpipe's own browser and talks to tvpipe over a local
//! API; phones' WebSockets are relayed to it; its TV page is rendered by a
//! headless browser and cast with the `share URL` machinery.
//!
//! - [`bundle`]: the manifest and the files (folders, zips).
//! - [`server`]: the listeners, their access rules, static files.
//! - [`hub`]: the API, the relay, discovery/pairing/cast progress.
//! - [`conn`]: one WebSocket with an outbox and limits.
//! - [`shortlink`]: short join links at tvpipe.party (docs/short-links.md).
//! - [`surface`]: canvases the pages encode, streamed without a browser.
//! - [`backend`]: discovery, pairing, casting, surfaces (fakes in tests).
//! - [`window`]: the app window.
//! - [`web`]: the library and the launcher, embedded.
//! - [`check`], [`scan`], [`smoke`], [`tool`]: `tvpipe game pack`/`check`/`new` (checks,
//!   packing, a run in a headless browser, the starter template).
//! - [`source`], [`remote`], [`cache`]: games from the internet (ยง18): what
//!   a source may be, fetching from GitHub and the games list, the cache.
//! - [`picker`]: `game play` without a game: the games list in the window
//!   first (docs/game-catalog.md).

pub mod backend;
pub mod bundle;
pub mod cache;
pub mod check;
pub mod conn;
pub mod hub;
pub mod picker;
pub mod remote;
pub mod resolution;
pub mod scan;
pub mod server;
pub mod shortlink;
pub mod smoke;
pub mod source;
pub mod surface;
pub mod tool;
pub mod web;
pub mod window;

use std::net::{IpAddr, SocketAddr};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use crate::ctx::Ctx;
use crate::error::{Error, Result};
use crate::events::{Events, Progress, Step};
use crate::net::httpd;
use crate::net::tunnel::Provider;
use crate::util::stop::Stop;

pub use bundle::Bundle;
pub use hub::Hub;
pub use window::WindowMode;

/// The LAN listener's port when free (`--lan`; the next of the following
/// 20 otherwise), as the old party host had it.
pub const LAN_PORT: u16 = 7420;
/// With a window we do not own: no page connected for this long ends
/// the run.
pub const ORPHAN_AFTER: Duration = Duration::from_secs(30);
const TICK: Duration = Duration::from_millis(200);

/// Who carries the phones' link.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TunnelChoice {
    /// OpenTunnel (its identity is reused), else Cloudflare.
    #[default]
    Auto,
    Provider(Provider),
    /// No public link (`--no-tunnel`).
    Off,
}

/// `tvpipe game play` (the CLI's options).
#[derive(Debug, Clone, Default)]
pub struct Options {
    /// The game: a folder, a `.zip`, an `https://` URL, `gh:โ€ฆ` or a name
    /// from the games list (ยง18); empty: the window picks one from the
    /// list (docs/game-catalog.md).
    pub game: String,
    /// `--refresh`, `--offline`.
    pub fetch: remote::FetchOptions,
    /// `--yes`: a game from the internet runs without the question.
    pub yes: bool,
    pub tunnel: TunnelChoice,
    /// `--lan [IP]`: `Some(None)` for the default route's address.
    pub lan: Option<Option<IpAddr>>,
    pub window: WindowMode,
    /// `--browser`: the window's and the TV's browser.
    pub browser: Option<PathBuf>,
    /// The local listener's port (0: any).
    pub port: u16,
    /// `--resolution`: the TV picture's at the start (the launcher and
    /// the cast picker change it).
    pub resolution: resolution::Resolution,
    /// `--no-short-link`: no short link at tvpipe.party.
    pub no_short_link: bool,
}

/// A started playshare: the hub, its listeners and the tunnel.
pub(crate) struct Running {
    pub hub: Arc<Hub>,
    servers: Servers,
    tunnel: TunnelThread,
}

impl Running {
    /// Binds the listeners and starts the tunnel (in the background).
    pub(crate) fn start(
        bundle: Bundle,
        backend: Box<dyn backend::Backend>,
        opts: &Options,
        stop: Stop,
    ) -> Result<Running> {
        Running::start_with(bundle, backend, opts, stop, Events::none())
    }

    /// [`Running::start`] with progress events for a front end.
    pub(crate) fn start_with(
        bundle: Bundle,
        backend: Box<dyn backend::Backend>,
        opts: &Options,
        stop: Stop,
        events: Events,
    ) -> Result<Running> {
        let token = crate::util::hex::encode(&crate::crypto::ring::random_array::<16>()?);
        let hub = Hub::new(bundle, token, backend, stop.clone());
        hub.set_resolution(opts.resolution);
        let _ = hub.events.set(events);
        let _ = hub.shortlinks.set(shortlink::ShortLinks::from_env(
            opts.no_short_link,
            stop.clone(),
        ));
        let servers = Servers::start(&hub, opts.port, opts.lan)?;
        let tunnel = start_tunnel(&hub, opts.tunnel);
        Ok(Running {
            hub,
            servers,
            tunnel,
        })
    }

    /// The window's first URL (it sets the session cookie).
    pub(crate) fn start_url(&self) -> String {
        format!(
            "http://127.0.0.1:{}/_tvpipe/start?t={}",
            self.hub.ports.get().map(|p| p.local).unwrap_or(0),
            self.hub.token
        )
    }

    /// The end (ยง10).
    pub(crate) fn end(self) {
        self.hub.shutdown();
        // While the tunnel still carries the link's target.
        if let Some(l) = self.hub.shortlinks.get() {
            l.release();
        }
        drop(self.tunnel);
        drop(self.servers);
    }
}

/// Asks the person a yes/no question (the text ends in `[y/N]`; the
/// function polls whether to give up): `Some(answer)`, or `None` when there
/// is nobody to ask.
pub type Ask<'a> = &'a dyn Fn(&str, &dyn Fn() -> bool) -> Option<bool>;

/// The game of `opts`: a local one as it is; one from the internet
/// fetched (or from the cache), and run only after the question (ยง18)
/// unless pinned, approved before or `--yes`.
pub fn open_game(opts: &Options, ctx: &Ctx, ask: Ask<'_>) -> Result<Bundle> {
    let src = source::Source::parse(&opts.game)?;
    if let source::Source::Local(p) = &src {
        return Bundle::open(p);
    }
    let fetcher =
        remote::Fetcher::from_env(opts.fetch, ctx.events.clone(), Some(ctx.stop.clone()))?;
    let f = fetcher.fetch(&src)?;
    if f.pinned || f.trusted || opts.yes {
        return Ok(f.bundle);
    }
    let stop = ctx.stop.clone();
    match ask(&f.question(), &|| stop.requested()) {
        Some(true) => {
            fetcher.trust(&f)?;
            Ok(f.bundle)
        }
        Some(false) => Err(Error::usage(format!(
            "not playing {}: you said no",
            f.bundle.manifest.name
        ))),
        None if stop.requested() => Err(Error::closed("stopped")),
        None => Err(Error::usage(format!(
            "{} is a game from the internet, and there is no terminal to ask whether to run it: \
             pass --yes, or pin it: tvpipe game play '{}'",
            f.shown, f.pin_hint
        ))),
    }
}

/// Runs playshare until the window closes, the page quits or `ctx`'s
/// stop is requested. Prints the window's URL with `--window none`. A
/// game from the internet is first fetched and, the first time, asked
/// about with `ask`. Without a game, the window opens on the games list
/// and the game picked there runs (docs/game-catalog.md).
pub fn run(opts: &Options, ctx: &Ctx, ask: Ask<'_>) -> Result<()> {
    if opts.game.trim().is_empty() {
        return run_picked(opts, ctx);
    }
    let bundle = open_game(opts, ctx, ask)?;
    let running = start_game(bundle, opts, ctx)?;
    let url = running.start_url();
    let window = match open_window(opts, &url, &ctx.events) {
        Ok(w) => w,
        Err(e) => {
            running.end();
            return Err(e);
        }
    };
    serve(running, window, &ctx.stop, &ctx.events);
    Ok(())
}

/// `game play` without a game: the picker in the window, then the game.
fn run_picked(opts: &Options, ctx: &Ctx) -> Result<()> {
    let stop = ctx.stop.clone();
    let picker = picker::Picker::start(opts.fetch, opts.yes, opts.port, stop.clone())?;
    let mut window = open_window(opts, &picker.start_url(), &ctx.events)?;
    info!("playshare: pick a game in the window");
    let bundle = loop {
        if stop.wait(TICK) {
            window.close();
            return Ok(());
        }
        if window.owned() {
            window.pass_out_new_pages();
            if window.closed() {
                info!("playshare: the window was closed");
                window.close();
                return Ok(());
            }
        }
        if let Some(b) = picker.take() {
            break b;
        }
    };
    let source = bundle.origin.display().to_string();
    // The game's own listener: --port was the picker's.
    let game_opts = Options {
        port: 0,
        ..opts.clone()
    };
    let running = match start_game(bundle, &game_opts, ctx) {
        Ok(r) => r,
        Err(e) => {
            picker.failed(&source, &e);
            // Long enough for the page to show it.
            stop.wait(Duration::from_secs(3));
            window.close();
            return Err(e);
        }
    };
    picker.started(running.start_url());
    serve(running, window, &stop, &ctx.events);
    drop(picker);
    Ok(())
}

/// Starts the game's server and tells the front end about it.
fn start_game(bundle: Bundle, opts: &Options, ctx: &Ctx) -> Result<Running> {
    let events = ctx.events.clone();
    info!(
        "playshare: {} from {}",
        bundle.manifest.title,
        bundle.origin.display()
    );
    let title = bundle.manifest.title.clone();
    let backend = backend::Real {
        storage: ctx.storage.clone(),
        browser: opts.browser.clone(),
    };
    let running = Running::start_with(
        bundle,
        Box::new(backend),
        opts,
        ctx.stop.clone(),
        events.clone(),
    )?;
    let p = *running
        .hub
        .ports
        .get()
        .ok_or_else(|| Error::closed("no ports"))?;
    let local = format!("http://127.0.0.1:{}/", p.public);
    let lan = p.lan.map(|lan| format!("http://{lan}/"));
    info!(
        "playshare: phones on this computer: {local}{}",
        lan.as_ref()
            .map(|l| format!(", on the Wi-Fi: {l}"))
            .unwrap_or_default()
    );
    events.progress(Progress::Game { title, local, lan });
    Ok(running)
}

/// Opens the window on `url` (prints it with `--window none`).
fn open_window(opts: &Options, url: &str, events: &Events) -> Result<window::Window> {
    if opts.window != WindowMode::None {
        events.progress(Progress::Begin(Step::Window));
    }
    let (window, mode) = match window::Window::open(opts.window, url, opts.browser.as_ref()) {
        Ok(w) => w,
        Err(e) => {
            events.progress(Progress::Failed(Step::Window, e.to_string()));
            return Err(e);
        }
    };
    if opts.window != WindowMode::None {
        events.progress(Progress::Done(Step::Window, None));
    }
    if mode == WindowMode::None {
        println!("{url}");
    }
    Ok(window)
}

/// Runs the game until the window closes, the page quits or a stop.
fn serve(running: Running, mut window: window::Window, stop: &Stop, events: &Events) {
    let hub = running.hub.clone();
    let mut phones = 0;
    let why = loop {
        if stop.wait(TICK) {
            break "stopped";
        }
        hub.tick();
        let n = hub.client_count();
        if n != phones {
            phones = n;
            events.progress(Progress::Phones(n));
        }
        if window.owned() {
            window.pass_out_new_pages();
            if window.closed() {
                break "the window was closed";
            }
        } else if hub.apis_gone_for().is_some_and(|d| d > ORPHAN_AFTER) {
            break "no page has been connected for 30 s";
        }
    };
    info!("playshare: ending ({why})");
    // The pages first (goodbyes to phones), then the window.
    running.end();
    window.close();
}

/// The listeners.
struct Servers {
    list: Vec<httpd::Server>,
}

impl Servers {
    fn start(hub: &Arc<Hub>, port: u16, lan: Option<Option<IpAddr>>) -> Result<Servers> {
        let config = httpd::Config {
            max_connections: hub.max_clients() + 64,
            max_body: 64 * 1024,
            lan: false,
        };
        let local = httpd::Server::bind_with(
            SocketAddr::from(([127, 0, 0, 1], port)),
            server::handler(hub.clone(), server::Listener::Local),
            config,
        )?;
        let public = httpd::Server::bind_with(
            SocketAddr::from(([127, 0, 0, 1], 0)),
            server::handler(hub.clone(), server::Listener::Public),
            config,
        )?;
        let mut list = vec![];
        let mut lan_addr = None;
        if let Some(ip) = lan {
            let ip = match ip {
                Some(ip) => ip,
                None => IpAddr::V4(crate::net::iface::default_ipv4()?),
            };
            let cfg = httpd::Config {
                lan: true,
                ..config
            };
            let mut bound = None;
            let mut last = None;
            for port in (LAN_PORT..LAN_PORT + 20).chain([0]) {
                match httpd::Server::bind_with(
                    SocketAddr::new(ip, port),
                    server::handler(hub.clone(), server::Listener::Lan),
                    cfg,
                ) {
                    Ok(s) => {
                        bound = Some(s);
                        break;
                    }
                    Err(e) => last = Some(e),
                }
            }
            let s = match bound {
                Some(s) => s,
                None => {
                    return Err(last.unwrap_or_else(|| Error::closed("no LAN port")));
                }
            };
            lan_addr = Some(s.local_addr());
            list.push(s);
        }
        let _ = hub.ports.set(hub::Ports {
            local: local.local_addr().port(),
            public: public.local_addr().port(),
            lan: lan_addr,
        });
        list.push(local);
        list.push(public);
        Ok(Servers { list })
    }
}

impl Drop for Servers {
    fn drop(&mut self) {
        for s in &mut self.list {
            s.shutdown();
        }
    }
}

/// A running tunnel, dropped at the end.
struct TunnelThread {
    slot: Arc<std::sync::Mutex<Option<Box<dyn crate::net::tunnel::Tunnel>>>>,
}

impl Drop for TunnelThread {
    fn drop(&mut self) {
        let t = self.slot.lock().unwrap_or_else(|e| e.into_inner()).take();
        drop(t);
    }
}

/// Starts the tunnel in the background (ยง11): the API reports it when it
/// is up.
fn start_tunnel(hub: &Arc<Hub>, choice: TunnelChoice) -> TunnelThread {
    let slot: Arc<std::sync::Mutex<Option<Box<dyn crate::net::tunnel::Tunnel>>>> = Arc::default();
    let order: Vec<Provider> = match choice {
        TunnelChoice::Off => return TunnelThread { slot },
        TunnelChoice::Auto => vec![Provider::OpenTunnel, Provider::Cloudflare],
        TunnelChoice::Provider(p) => vec![p],
    };
    let port = hub.ports.get().map(|p| p.public).unwrap_or(0);
    {
        let mut t = hub.tunnel.write().unwrap_or_else(|e| e.into_inner());
        t.state = "starting";
    }
    hub.progress(Progress::Begin(Step::Tunnel));
    let (hub, s) = (hub.clone(), slot.clone());
    let _ = std::thread::Builder::new()
        .name("playshare-tunnel".into())
        .spawn(move || {
            let stop = hub.stop.clone();
            let mut last_err = None;
            for p in order {
                if stop.requested() {
                    return;
                }
                let started = match p {
                    // The last quick tunnel again, if Cloudflare kept it.
                    Provider::Cloudflare => crate::storage::cli_dir()
                        .map(|d| d.join("cloudflare-quick-tunnel.json"))
                        .and_then(|f| {
                            crate::net::cftunnel::Tunnel::start_reusing(port, &f, &|| {
                                stop.requested()
                            })
                        })
                        .map(|t| Box::new(t) as Box<dyn crate::net::tunnel::Tunnel>),
                    _ => crate::net::tunnel::start(port, p, &|| stop.requested()),
                };
                match started {
                    Ok(t) => {
                        info!(
                            "playshare: phones join at https://{}/ ({})",
                            t.host(),
                            t.name()
                        );
                        {
                            let mut info = hub.tunnel.write().unwrap_or_else(|e| e.into_inner());
                            info.state = "up";
                            info.provider = Some(p.name().to_owned());
                            info.host = Some(t.host().to_owned());
                            info.error = None;
                        }
                        hub.progress(Progress::GameLink {
                            url: format!("https://{}/", t.host()),
                            provider: p.name().to_owned(),
                            short: hub.shortlinks.get().is_some_and(|l| l.enabled()),
                        });
                        *hub.peers.write().unwrap_or_else(|e| e.into_inner()) = t.peer_lookup();
                        *s.lock().unwrap_or_else(|e| e.into_inner()) = Some(t);
                        if stop.requested() {
                            s.lock().unwrap_or_else(|e| e.into_inner()).take();
                            return;
                        }
                        hub.tunnel_changed();
                        return;
                    }
                    Err(e) => {
                        warn!("playshare: {} tunnel: {e}", p.name());
                        last_err = Some(e.to_string());
                    }
                }
            }
            hub.progress(Progress::Failed(
                Step::Tunnel,
                last_err.clone().unwrap_or_else(|| "no tunnel".into()),
            ));
            {
                let mut info = hub.tunnel.write().unwrap_or_else(|e| e.into_inner());
                info.state = "failed";
                info.error = last_err;
            }
            hub.tunnel_changed();
        });
    TunnelThread { slot }
}

#[cfg(test)]
mod tests;