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
//! What sessions and commands report: [`Event`], the typed form of the
//! machine interface's events (docs/machine.md), and [`Events`], the
//! per-session handle they go out through.
//!
//! The machine protocol is the JSON serialization of these types
//! ([`Event::to_json`]); wire names are as in docs/machine.md
//! (`gave-up`, `share-page`, snake_case fields). [`Event::from_json`]
//! reads them back, for programs that run `tvpipe --machine`.

use std::sync::Arc;

use crate::codec::json::Value;
use crate::error::{Error, Result};

/// One thing that happened in a session or a command.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Event {
    /// The first event of `tvpipe --machine`; library sessions never send
    /// it.
    Hello(Hello),
    /// A log line of `tvpipe --machine`; library sessions never send it
    /// (log lines go to the logger, see [`crate::log`]).
    Log(crate::log::Record),
    /// A receiver changed state.
    Receiver(ReceiverEvent),
    /// A `browser` receiver's page listens.
    Player(PlayerEvent),
    /// A tab connected to or left a `browser` receiver's page.
    Viewer(ViewerEvent),
    /// A public link (`tunnel`) to the player or share page works.
    Tunnel(TunnelEvent),
    /// `share` without a URL: the page to open and share from.
    SharePage(SharePageEvent),
    /// `share` or `screen`: the browser started sharing.
    Capture(CaptureEvent),
    /// Every receiver that could be connected is; the input opens next.
    Connected(ConnectedEvent),
    /// The input is open and the receivers started.
    Started(Started),
    /// A receiver needs an IDR (programs sending their own H.264).
    Keyframe,
    /// Once a second while frames flow.
    Stats(Stats),
    /// `discover`'s result.
    Devices(DevicesEvent),
    /// Pairing needs the PIN the TV shows.
    PinRequired(PinRequest),
    /// Pairing succeeded and was verified.
    Paired(Paired),
    /// A pairing was forgotten.
    Unpaired(Unpaired),
    /// The session or command is over.
    End(EndInfo),
    /// The session or command failed.
    Error(ErrorInfo),
}

/// Defines a string enum with its wire names.
macro_rules! wire_enum {
    ($(#[$m:meta])* $name:ident { $($(#[$vm:meta])* $v:ident = $s:literal),+ $(,)? }) => {
        $(#[$m])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        #[allow(missing_docs)]
        pub enum $name { $($(#[$vm])* $v),+ }

        impl $name {
            /// The name on the wire (docs/machine.md).
            pub fn as_str(self) -> &'static str {
                match self { $($name::$v => $s),+ }
            }

            /// Parses a wire name.
            pub fn from_wire(s: &str) -> Option<$name> {
                match s { $($s => Some($name::$v),)+ _ => None }
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(self.as_str())
            }
        }
    };
}

wire_enum!(
    /// A receiver's protocol.
    Protocol {
        Cast = "cast",
        AirPlay = "airplay",
        Browser = "browser",
    }
);

wire_enum!(
    /// A receiver's state in [`ReceiverEvent`].
    ReceiverState {
        /// Connected and ready to play.
        Connected = "connected",
        /// Could not resolve, connect or start, or failed mid-stream.
        Failed = "failed",
        /// The connection broke; reconnecting.
        Lost = "lost",
        /// Back after [`Lost`](ReceiverState::Lost).
        Reconnected = "reconnected",
        /// Reconnecting failed.
        GaveUp = "gave-up",
        /// The receiver's user ended the session.
        Ended = "ended",
        /// tvpipe stopped it (the session ended).
        Stopped = "stopped",
    }
);

wire_enum!(
    /// A tab of a `browser` receiver.
    ViewerState {
        Connected = "connected",
        Disconnected = "disconnected",
    }
);

wire_enum!(
    /// Which page a public link leads to.
    TunnelPage {
        /// A `browser` receiver's player page.
        Player = "player",
        /// The share page.
        Share = "share",
    }
);

wire_enum!(
    /// Where the frames come from.
    Route {
        /// A file sent unchanged.
        Passthrough = "passthrough",
        /// Encoded by ffmpeg.
        Ffmpeg = "ffmpeg",
        /// Raw frames or the test pattern through the built-in encoder.
        Builtin = "builtin",
        /// The program's own H.264.
        Encoded = "encoded",
        /// A browser page's capture (`share`, `screen`).
        Browser = "browser",
    }
);

wire_enum!(
    /// Why a session ended.
    EndReason {
        /// The input ended (and its tail played out).
        Eof = "eof",
        /// Stopped on request.
        Stopped = "stopped",
        /// Every receiver ended the session.
        ReceiversGone = "receivers-gone",
        /// The input failed.
        Error = "error",
        /// A command without a stream finished.
        Done = "done",
    }
);

wire_enum!(
    /// How one receiver ended.
    ReceiverEnd {
        Stopped = "stopped",
        Ended = "ended",
        Failed = "failed",
    }
);

/// `hello`: the machine interface's first event.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hello {
    /// The machine protocol version (1).
    pub protocol: u32,
    /// tvpipe's version.
    pub version: String,
    /// The command (`play` also for `preview`, `test-pattern`, …).
    pub command: String,
}

impl Hello {
    /// A `hello` event.
    pub fn new(protocol: u32, version: impl Into<String>, command: impl Into<String>) -> Hello {
        Hello {
            protocol,
            version: version.into(),
            command: command.into(),
        }
    }
}

/// A receiver's state change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverEvent {
    /// The receiver, as given (`--to`) or as discovered.
    pub name: String,
    /// Known on `connected`, and on `failed` while connecting.
    pub protocol: Option<Protocol>,
    /// What happened.
    pub state: ReceiverState,
    /// What went wrong (`failed`, `lost`, `gave-up`).
    pub error: Option<String>,
    /// A stable code for the error, e.g. `pairing-required`.
    pub code: Option<String>,
}

impl ReceiverEvent {
    pub(crate) fn new(
        name: &str,
        protocol: Option<Protocol>,
        state: ReceiverState,
        error: Option<&Error>,
    ) -> ReceiverEvent {
        ReceiverEvent {
            name: name.to_owned(),
            protocol,
            state,
            error: error.map(|e| e.to_string()),
            code: error.and_then(|e| e.code()).map(str::to_owned),
        }
    }
}

/// A `browser` receiver's page.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlayerEvent {
    /// The receiver (`browser`).
    pub name: String,
    /// Open it in a browser to watch.
    pub url: String,
}

/// A tab of a `browser` receiver connected or left.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ViewerEvent {
    /// The receiver (`browser`).
    pub name: String,
    /// The tab, numbered from 1 per receiver.
    pub tab: u64,
    /// Connected or left.
    pub state: ViewerState,
    /// It came over the public link.
    pub public: bool,
}

/// A public link works.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TunnelEvent {
    /// The page it leads to.
    pub page: TunnelPage,
    /// The player's name (`page` = player).
    pub name: Option<String>,
    /// Who carries it: `cloudflare` or `opentunnel`.
    pub provider: String,
    /// The link, with its token.
    pub url: String,
}

/// The page `share` serves.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SharePageEvent {
    /// The page; open it and press Share.
    pub url: String,
}

/// What a share captures.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CaptureEvent {
    /// `monitor`, `window` or `browser`, if the browser says.
    pub surface: Option<String>,
    /// What the browser calls it (a screen or window title), if it says.
    pub label: Option<String>,
    /// The capture's width.
    pub width: u32,
    /// The capture's height.
    pub height: u32,
    /// Whether the capture has sound.
    pub audio: bool,
}

/// The receivers connected.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConnectedEvent {
    /// The receivers that connected, by name.
    pub receivers: Vec<String>,
}

/// The video being sent.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct VideoStarted {
    /// `h264`.
    pub codec: String,
    /// Encoded width.
    pub width: u32,
    /// Encoded height.
    pub height: u32,
    /// Frames per second.
    pub fps: f64,
}

/// One audio track being sent (one per receiver family).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioStarted {
    /// `alac`, `aac-lc`, `opus`, `pcm-s16le`, …
    pub codec: String,
    /// Samples per second.
    pub sample_rate: u32,
    /// Channels.
    pub channels: u8,
}

/// The plan once streaming started.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Started {
    /// Where the frames come from.
    pub route: Route,
    /// The video.
    pub video: VideoStarted,
    /// One audio track per receiver family.
    pub audio: Vec<AudioStarted>,
    /// The playout delay every receiver presents frames with.
    pub latency_ms: u32,
}

/// Counters of one receiver.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverStats {
    /// The receiver.
    pub name: String,
    /// Frames handed to the receiver's sink.
    pub pushed: u64,
    /// Frames the sink dropped (its writer was full).
    pub dropped: u64,
    /// Frames dropped because the receiver's queue was full.
    pub dropped_full: u64,
    /// Frames dropped while waiting for a keyframe.
    pub dropped_waiting: u64,
}

/// Once a second while frames flow.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stats {
    /// Time since streaming started.
    pub elapsed_ms: u64,
    /// Video frames sent so far.
    pub video_frames: u64,
    /// Audio frames sent so far.
    pub audio_frames: u64,
    /// Per receiver.
    pub receivers: Vec<ReceiverStats>,
}

/// `discover`'s devices.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DevicesEvent {
    /// What was found.
    pub devices: Vec<crate::net::discover::DeviceInfo>,
}

/// Pairing needs a PIN.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PinRequest {
    /// The receiver's name.
    pub name: String,
    /// Its address (`ip:port`).
    pub address: String,
}

/// A pairing succeeded.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Paired {
    /// The receiver.
    pub name: String,
    /// Its model, if it said.
    pub model: Option<String>,
    /// The credentials file, when the storage is a directory.
    pub file: Option<String>,
}

/// A pairing was forgotten.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Unpaired {
    /// The receiver.
    pub name: String,
    /// Its pairing identifier.
    pub id: String,
}

/// How one receiver ended, with its counters.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverEndInfo {
    /// Its counters.
    pub stats: ReceiverStats,
    /// How it ended.
    pub end: ReceiverEnd,
    /// What went wrong (`failed`).
    pub error: Option<String>,
}

/// How a session or command ended.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EndInfo {
    /// Why.
    pub reason: EndReason,
    /// Per receiver (sessions only; `None` for commands without a stream).
    pub receivers: Option<Vec<ReceiverEndInfo>>,
}

impl EndInfo {
    /// An end without per-receiver details.
    pub fn new(reason: EndReason) -> EndInfo {
        EndInfo {
            reason,
            receivers: None,
        }
    }
}

/// A failure, as the `error` event carries it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorInfo {
    /// The error kind's wire name (`io`, `auth`, …).
    pub kind: String,
    /// A stable code (`pairing-required`, …), where the case is known.
    pub code: Option<String>,
    /// What went wrong, for people.
    pub message: String,
    /// The receiver the error is about.
    pub device: Option<String>,
}

impl From<&Error> for ErrorInfo {
    fn from(e: &Error) -> ErrorInfo {
        ErrorInfo {
            kind: e.kind().id().to_owned(),
            code: e.code().map(str::to_owned),
            message: e.to_string(),
            device: e.device().map(str::to_owned),
        }
    }
}

// ---------------------------------------------------------------------------
// JSON

fn stats_json(st: &ReceiverStats) -> Value {
    Value::object()
        .with("name", st.name.as_str())
        .with("pushed", st.pushed)
        .with("dropped", st.dropped)
        .with("dropped_full", st.dropped_full)
        .with("dropped_waiting", st.dropped_waiting)
}

fn stats_from(v: &Value) -> Result<ReceiverStats> {
    Ok(ReceiverStats {
        name: v.require_str("name")?.to_owned(),
        pushed: v.require_u64("pushed")?,
        dropped: v.require_u64("dropped")?,
        dropped_full: v.require_u64("dropped_full")?,
        dropped_waiting: v.require_u64("dropped_waiting")?,
    })
}

fn opt_str(v: &Value, key: &str) -> Option<String> {
    v.get(key).and_then(Value::as_str).map(str::to_owned)
}

fn wire<T>(v: &Value, key: &str, parse: fn(&str) -> Option<T>) -> Result<T> {
    let s = v.require_str(key)?;
    parse(s).ok_or_else(|| Error::malformed(format!("event: unknown {key} {s:?}")))
}

fn list<T>(v: &Value, key: &str, f: impl Fn(&Value) -> Result<T>) -> Result<Vec<T>> {
    v.require_array(key)?.iter().map(f).collect()
}

impl Event {
    /// The event's `type` on the wire.
    pub fn type_name(&self) -> &'static str {
        match self {
            Event::Hello(_) => "hello",
            Event::Log(_) => "log",
            Event::Receiver(_) => "receiver",
            Event::Player(_) => "player",
            Event::Viewer(_) => "viewer",
            Event::Tunnel(_) => "tunnel",
            Event::SharePage(_) => "share-page",
            Event::Capture(_) => "capture",
            Event::Connected(_) => "connected",
            Event::Started(_) => "started",
            Event::Keyframe => "keyframe",
            Event::Stats(_) => "stats",
            Event::Devices(_) => "devices",
            Event::PinRequired(_) => "pin-required",
            Event::Paired(_) => "paired",
            Event::Unpaired(_) => "unpaired",
            Event::End(_) => "end",
            Event::Error(_) => "error",
        }
    }

    /// The event as a JSON value (one machine-interface line).
    pub(crate) fn to_value(&self) -> Value {
        let v = Value::object().with("type", self.type_name());
        match self {
            Event::Hello(h) => v
                .with("protocol", h.protocol)
                .with("version", h.version.as_str())
                .with("command", h.command.as_str()),
            Event::Log(r) => v
                .with("level", r.level.as_str())
                .with("module", r.module.as_str())
                .with("message", r.message.as_str()),
            Event::Receiver(r) => v
                .with("name", r.name.as_str())
                .with_opt("protocol", r.protocol.map(Protocol::as_str))
                .with("state", r.state.as_str())
                .with_opt("error", r.error.as_deref())
                .with_opt("code", r.code.as_deref()),
            Event::Player(p) => v.with("name", p.name.as_str()).with("url", p.url.as_str()),
            Event::Viewer(w) => v
                .with("name", w.name.as_str())
                .with("tab", w.tab)
                .with("state", w.state.as_str())
                .with("public", w.public),
            Event::Tunnel(t) => v
                .with("page", t.page.as_str())
                .with_opt("name", t.name.as_deref())
                .with("provider", t.provider.as_str())
                .with("url", t.url.as_str()),
            Event::SharePage(p) => v.with("url", p.url.as_str()),
            Event::Capture(c) => v
                .with_opt("surface", c.surface.as_deref())
                .with_opt("label", c.label.as_deref())
                .with("width", c.width)
                .with("height", c.height)
                .with("audio", c.audio),
            Event::Connected(c) => v.with(
                "receivers",
                Value::array(c.receivers.iter().map(String::as_str)),
            ),
            Event::Started(s) => v
                .with("route", s.route.as_str())
                .with(
                    "video",
                    Value::object()
                        .with("codec", s.video.codec.as_str())
                        .with("width", s.video.width)
                        .with("height", s.video.height)
                        .with("fps", s.video.fps),
                )
                .with(
                    "audio",
                    Value::array(s.audio.iter().map(|a| {
                        Value::object()
                            .with("codec", a.codec.as_str())
                            .with("sample_rate", a.sample_rate)
                            .with("channels", a.channels)
                    })),
                )
                .with("latency_ms", s.latency_ms),
            Event::Keyframe => v,
            Event::Stats(s) => v
                .with("elapsed_ms", s.elapsed_ms)
                .with("video_frames", s.video_frames)
                .with("audio_frames", s.audio_frames)
                .with(
                    "receivers",
                    Value::array(s.receivers.iter().map(stats_json)),
                ),
            Event::Devices(d) => v.with(
                "devices",
                Value::array(d.devices.iter().map(|d| d.to_value())),
            ),
            Event::PinRequired(p) => v
                .with("name", p.name.as_str())
                .with("address", p.address.as_str()),
            Event::Paired(p) => v
                .with("name", p.name.as_str())
                .with_opt("model", p.model.as_deref())
                .with_opt("file", p.file.as_deref()),
            Event::Unpaired(u) => v.with("name", u.name.as_str()).with("id", u.id.as_str()),
            Event::End(e) => v.with("reason", e.reason.as_str()).with_opt(
                "receivers",
                e.receivers.as_ref().map(|r| {
                    Value::array(r.iter().map(|r| {
                        stats_json(&r.stats)
                            .with("end", r.end.as_str())
                            .with_opt("error", r.error.as_deref())
                    }))
                }),
            ),
            Event::Error(e) => v
                .with("kind", e.kind.as_str())
                .with_opt("code", e.code.as_deref())
                .with("message", e.message.as_str())
                .with_opt("device", e.device.as_deref()),
        }
    }

    /// The event as one line of JSON (without the newline), as
    /// `tvpipe --machine` writes it.
    pub fn to_json(&self) -> String {
        self.to_value().to_json()
    }

    /// Parses one machine-interface line. Unknown fields are ignored; an
    /// unknown `type` is an error (readers skip those lines).
    pub fn from_json(line: &str) -> Result<Event> {
        Event::from_value(&Value::parse(line)?)
    }

    pub(crate) fn from_value(v: &Value) -> Result<Event> {
        let ty = v.require_str("type")?;
        Ok(match ty {
            "hello" => Event::Hello(Hello {
                protocol: v.require_u32("protocol")?,
                version: v.require_str("version")?.to_owned(),
                command: v.require_str("command")?.to_owned(),
            }),
            "log" => Event::Log(crate::log::Record {
                level: wire(v, "level", crate::log::Level::from_wire)?,
                module: v.require_str("module")?.to_owned(),
                message: v.require_str("message")?.to_owned(),
            }),
            "receiver" => Event::Receiver(ReceiverEvent {
                name: v.require_str("name")?.to_owned(),
                protocol: match v.get("protocol") {
                    Some(_) => Some(wire(v, "protocol", Protocol::from_wire)?),
                    None => None,
                },
                state: wire(v, "state", ReceiverState::from_wire)?,
                error: opt_str(v, "error"),
                code: opt_str(v, "code"),
            }),
            "player" => Event::Player(PlayerEvent {
                name: v.require_str("name")?.to_owned(),
                url: v.require_str("url")?.to_owned(),
            }),
            "viewer" => Event::Viewer(ViewerEvent {
                name: v.require_str("name")?.to_owned(),
                tab: v.require_u64("tab")?,
                state: wire(v, "state", ViewerState::from_wire)?,
                public: v.get("public").and_then(Value::as_bool).unwrap_or(false),
            }),
            "tunnel" => Event::Tunnel(TunnelEvent {
                page: wire(v, "page", TunnelPage::from_wire)?,
                name: opt_str(v, "name"),
                provider: v.require_str("provider")?.to_owned(),
                url: v.require_str("url")?.to_owned(),
            }),
            "share-page" => Event::SharePage(SharePageEvent {
                url: v.require_str("url")?.to_owned(),
            }),
            "capture" => Event::Capture(CaptureEvent {
                surface: opt_str(v, "surface"),
                label: opt_str(v, "label"),
                width: v.require_u32("width")?,
                height: v.require_u32("height")?,
                audio: v.require_bool("audio")?,
            }),
            "connected" => Event::Connected(ConnectedEvent {
                receivers: list(v, "receivers", |r| {
                    r.as_str()
                        .map(str::to_owned)
                        .ok_or_else(|| Error::malformed("event: receiver name not a string"))
                })?,
            }),
            "started" => {
                let video = v.require("video")?;
                Event::Started(Started {
                    route: wire(v, "route", Route::from_wire)?,
                    video: VideoStarted {
                        codec: video.require_str("codec")?.to_owned(),
                        width: video.require_u32("width")?,
                        height: video.require_u32("height")?,
                        fps: video.require_f64("fps")?,
                    },
                    audio: list(v, "audio", |a| {
                        Ok(AudioStarted {
                            codec: a.require_str("codec")?.to_owned(),
                            sample_rate: a.require_u32("sample_rate")?,
                            channels: u8::try_from(a.require_u32("channels")?)
                                .map_err(|_| Error::malformed("event: too many channels"))?,
                        })
                    })?,
                    latency_ms: v.require_u32("latency_ms")?,
                })
            }
            "keyframe" => Event::Keyframe,
            "stats" => Event::Stats(Stats {
                elapsed_ms: v.require_u64("elapsed_ms")?,
                video_frames: v.require_u64("video_frames")?,
                audio_frames: v.require_u64("audio_frames")?,
                receivers: list(v, "receivers", stats_from)?,
            }),
            "devices" => Event::Devices(DevicesEvent {
                devices: list(v, "devices", crate::net::discover::DeviceInfo::from_value)?,
            }),
            "pin-required" => Event::PinRequired(PinRequest {
                name: v.require_str("name")?.to_owned(),
                address: v.require_str("address")?.to_owned(),
            }),
            "paired" => Event::Paired(Paired {
                name: v.require_str("name")?.to_owned(),
                model: opt_str(v, "model"),
                file: opt_str(v, "file"),
            }),
            "unpaired" => Event::Unpaired(Unpaired {
                name: v.require_str("name")?.to_owned(),
                id: v.require_str("id")?.to_owned(),
            }),
            "end" => Event::End(EndInfo {
                reason: wire(v, "reason", EndReason::from_wire)?,
                receivers: match v.get("receivers") {
                    Some(_) => Some(list(v, "receivers", |r| {
                        Ok(ReceiverEndInfo {
                            stats: stats_from(r)?,
                            end: wire(r, "end", ReceiverEnd::from_wire)?,
                            error: opt_str(r, "error"),
                        })
                    })?),
                    None => None,
                },
            }),
            "error" => Event::Error(ErrorInfo {
                kind: v.require_str("kind")?.to_owned(),
                code: opt_str(v, "code"),
                message: v.require_str("message")?.to_owned(),
                device: opt_str(v, "device"),
            }),
            other => return Err(Error::unsupported(format!("event: unknown type {other:?}"))),
        })
    }
}

// ---------------------------------------------------------------------------
// The handle

type Sink = dyn Fn(Event) + Send + Sync;

/// Where a session's events go: nowhere by default, or a function (the
/// API's queue and callback, the CLI's `--machine` lines). Cloning shares
/// the destination.
#[derive(Clone, Default)]
pub struct Events(Option<Arc<Sink>>);

impl Events {
    /// Events that go nowhere.
    pub fn none() -> Events {
        Events(None)
    }

    /// Events handed to `f`, on whatever thread emits them (so `f` must be
    /// quick).
    pub fn to(f: impl Fn(Event) + Send + Sync + 'static) -> Events {
        Events(Some(Arc::new(f)))
    }

    /// Whether anything listens (skip building events nobody reads).
    pub fn active(&self) -> bool {
        self.0.is_some()
    }

    /// Sends an event.
    pub fn emit(&self, e: Event) {
        if let Some(f) = &self.0 {
            f(e);
        }
    }

    /// A [`ReceiverEvent`].
    pub(crate) fn receiver(
        &self,
        name: &str,
        protocol: Option<Protocol>,
        state: ReceiverState,
        error: Option<&Error>,
    ) {
        if self.active() {
            self.emit(Event::Receiver(ReceiverEvent::new(
                name, protocol, state, error,
            )));
        }
    }
}

impl std::fmt::Debug for Events {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(if self.active() {
            "Events(active)"
        } else {
            "Events(none)"
        })
    }
}

#[cfg(test)]
mod tests;