use std::sync::Arc;
use crate::codec::json::Value;
use crate::error::{Error, Result};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Event {
Hello(Hello),
Log(crate::log::Record),
Receiver(ReceiverEvent),
Player(PlayerEvent),
Viewer(ViewerEvent),
Tunnel(TunnelEvent),
SharePage(SharePageEvent),
Capture(CaptureEvent),
Connected(ConnectedEvent),
Started(Started),
Keyframe,
Stats(Stats),
Devices(DevicesEvent),
PinRequired(PinRequest),
Paired(Paired),
Unpaired(Unpaired),
End(EndInfo),
Error(ErrorInfo),
}
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 {
pub fn as_str(self) -> &'static str {
match self { $($name::$v => $s),+ }
}
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!(
Protocol {
Cast = "cast",
AirPlay = "airplay",
Browser = "browser",
}
);
wire_enum!(
ReceiverState {
Connected = "connected",
Failed = "failed",
Lost = "lost",
Reconnected = "reconnected",
GaveUp = "gave-up",
Ended = "ended",
Stopped = "stopped",
}
);
wire_enum!(
ViewerState {
Connected = "connected",
Disconnected = "disconnected",
}
);
wire_enum!(
TunnelPage {
Player = "player",
Share = "share",
}
);
wire_enum!(
Route {
Passthrough = "passthrough",
Ffmpeg = "ffmpeg",
Builtin = "builtin",
Encoded = "encoded",
Browser = "browser",
}
);
wire_enum!(
EndReason {
Eof = "eof",
Stopped = "stopped",
ReceiversGone = "receivers-gone",
Error = "error",
Done = "done",
}
);
wire_enum!(
ReceiverEnd {
Stopped = "stopped",
Ended = "ended",
Failed = "failed",
}
);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hello {
pub protocol: u32,
pub version: String,
pub command: String,
}
impl Hello {
pub fn new(protocol: u32, version: impl Into<String>, command: impl Into<String>) -> Hello {
Hello {
protocol,
version: version.into(),
command: command.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverEvent {
pub name: String,
pub protocol: Option<Protocol>,
pub state: ReceiverState,
pub error: Option<String>,
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),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlayerEvent {
pub name: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ViewerEvent {
pub name: String,
pub tab: u64,
pub state: ViewerState,
pub public: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct TunnelEvent {
pub page: TunnelPage,
pub name: Option<String>,
pub provider: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SharePageEvent {
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CaptureEvent {
pub surface: Option<String>,
pub label: Option<String>,
pub width: u32,
pub height: u32,
pub audio: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConnectedEvent {
pub receivers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct VideoStarted {
pub codec: String,
pub width: u32,
pub height: u32,
pub fps: f64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct AudioStarted {
pub codec: String,
pub sample_rate: u32,
pub channels: u8,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Started {
pub route: Route,
pub video: VideoStarted,
pub audio: Vec<AudioStarted>,
pub latency_ms: u32,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverStats {
pub name: String,
pub pushed: u64,
pub dropped: u64,
pub dropped_full: u64,
pub dropped_waiting: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stats {
pub elapsed_ms: u64,
pub video_frames: u64,
pub audio_frames: u64,
pub receivers: Vec<ReceiverStats>,
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct DevicesEvent {
pub devices: Vec<crate::net::discover::DeviceInfo>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PinRequest {
pub name: String,
pub address: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Paired {
pub name: String,
pub model: Option<String>,
pub file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Unpaired {
pub name: String,
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ReceiverEndInfo {
pub stats: ReceiverStats,
pub end: ReceiverEnd,
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EndInfo {
pub reason: EndReason,
pub receivers: Option<Vec<ReceiverEndInfo>>,
}
impl EndInfo {
pub fn new(reason: EndReason) -> EndInfo {
EndInfo {
reason,
receivers: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ErrorInfo {
pub kind: String,
pub code: Option<String>,
pub message: String,
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),
}
}
}
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 {
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",
}
}
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()),
}
}
pub fn to_json(&self) -> String {
self.to_value().to_json()
}
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:?}"))),
})
}
}
type Sink = dyn Fn(Event) + Send + Sync;
#[derive(Clone, Default)]
pub struct Events(Option<Arc<Sink>>);
impl Events {
pub fn none() -> Events {
Events(None)
}
pub fn to(f: impl Fn(Event) + Send + Sync + 'static) -> Events {
Events(Some(Arc::new(f)))
}
pub fn active(&self) -> bool {
self.0.is_some()
}
pub fn emit(&self, e: Event) {
if let Some(f) = &self.0 {
f(e);
}
}
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;