Add Store support and unsigned app releases
This commit is contained in:
16
crates/sf-miracast/Cargo.toml
Normal file
16
crates/sf-miracast/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "sf-miracast"
|
||||
description = "Experimental Miracast (Wi-Fi Display) sink for Fennec OS: iwd P2P + WFD RTSP + GStreamer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "macros", "process", "signal", "sync"] }
|
||||
libc = "0.2"
|
||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||
301
crates/sf-miracast/src/linux.rs
Normal file
301
crates/sf-miracast/src/linux.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
//! iwd P2P control, the RTSP session loop and the GStreamer player.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use zbus::Connection;
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
|
||||
use crate::rtsp::{Event, Message, SOURCE_PORT, Sink};
|
||||
|
||||
const IWD: &str = "net.connman.iwd";
|
||||
const P2P_DEVICE: &str = "net.connman.iwd.p2p.Device";
|
||||
const P2P_PEER: &str = "net.connman.iwd.p2p.Peer";
|
||||
const P2P_DISPLAY: &str = "net.connman.iwd.p2p.Display";
|
||||
const SERVICE_MANAGER: &str = "net.connman.iwd.p2p.ServiceManager";
|
||||
const RTP_PORT: u16 = 1028;
|
||||
/// A source peer must be visible this long before we connect to it.
|
||||
const SETTLE: Duration = Duration::from_secs(2);
|
||||
|
||||
type Props = HashMap<String, OwnedValue>;
|
||||
type Objects = HashMap<OwnedObjectPath, HashMap<String, Props>>;
|
||||
|
||||
fn event(text: &str) {
|
||||
let mut out = std::io::stdout().lock();
|
||||
let _ = writeln!(out, "SF-EVENT {text}");
|
||||
let _ = out.flush();
|
||||
}
|
||||
|
||||
fn get_bool(p: &Props, k: &str) -> Option<bool> {
|
||||
p.get(k).and_then(|v| bool::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
fn get_str(p: &Props, k: &str) -> Option<String> {
|
||||
p.get(k).and_then(|v| String::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
fn get_u16(p: &Props, k: &str) -> Option<u16> {
|
||||
p.get(k).and_then(|v| u16::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
async fn objects(conn: &Connection) -> Result<Objects> {
|
||||
let om = zbus::fdo::ObjectManagerProxy::builder(conn).destination(IWD)?.path("/")?.build().await?;
|
||||
let raw = om.get_managed_objects().await?;
|
||||
Ok(raw
|
||||
.into_iter()
|
||||
.map(|(path, ifaces)| (path, ifaces.into_iter().map(|(k, v)| (k.to_string(), v)).collect()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn proxy<'a>(conn: &Connection, path: &'a str, iface: &'a str) -> Result<zbus::Proxy<'a>> {
|
||||
Ok(zbus::Proxy::new(conn, IWD, path, iface).await?)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Peer {
|
||||
path: String,
|
||||
name: String,
|
||||
connected: bool,
|
||||
ip: Option<String>,
|
||||
source: bool,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
fn peers(objs: &Objects) -> Vec<Peer> {
|
||||
objs.iter()
|
||||
.filter_map(|(path, ifaces)| {
|
||||
let p = ifaces.get(P2P_PEER)?;
|
||||
let display = ifaces.get(P2P_DISPLAY);
|
||||
Some(Peer {
|
||||
path: path.to_string(),
|
||||
name: get_str(p, "Name").unwrap_or_else(|| "telefon".into()),
|
||||
connected: get_bool(p, "Connected").unwrap_or(false),
|
||||
ip: get_str(p, "ConnectedIP"),
|
||||
source: display.and_then(|d| get_bool(d, "Source")).unwrap_or(false),
|
||||
port: display.and_then(|d| get_u16(d, "Port")).filter(|p| *p != 0).unwrap_or(SOURCE_PORT),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn run(name: String) -> Result<()> {
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
rt.block_on(main_loop(name))
|
||||
}
|
||||
|
||||
async fn main_loop(name: String) -> Result<()> {
|
||||
let conn = Connection::system().await.context("system D-Bus")?;
|
||||
let mut setup_for: Option<String> = None;
|
||||
let mut warned = false;
|
||||
let mut first_seen: HashMap<String, Instant> = HashMap::new();
|
||||
let mut backoff: HashMap<String, Instant> = HashMap::new();
|
||||
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let objs = match objects(&conn).await {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
if !warned {
|
||||
log::warn!("iwd: {e:#}");
|
||||
warned = true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(9)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(device) = objs.iter().find(|(_, i)| i.contains_key(P2P_DEVICE)).map(|(p, _)| p.to_string()) else {
|
||||
if !warned {
|
||||
log::warn!("no Wi-Fi Direct (P2P) capable Wi-Fi device; Miracast is unavailable");
|
||||
warned = true;
|
||||
}
|
||||
setup_for = None;
|
||||
tokio::time::sleep(Duration::from_secs(9)).await;
|
||||
continue;
|
||||
};
|
||||
warned = false;
|
||||
if setup_for.as_deref() != Some(device.as_str()) {
|
||||
match setup(&conn, &device, &name).await {
|
||||
Ok(()) => {
|
||||
log::info!("Wi-Fi Display sink \"{name}\" ready on {device}");
|
||||
setup_for = Some(device.clone());
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("p2p setup: {e:#}");
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
backoff.retain(|_, until| *until > now);
|
||||
let list = peers(&objs);
|
||||
let visible: HashSet<String> = list.iter().map(|p| p.path.clone()).collect();
|
||||
first_seen.retain(|k, _| visible.contains(k));
|
||||
|
||||
// Already connected (e.g. we connected in an earlier round).
|
||||
let target = match list.iter().find(|p| p.connected) {
|
||||
Some(p) => Some(p.clone()),
|
||||
None => {
|
||||
let candidate = list.iter().find(|p| p.source && !backoff.contains_key(&p.path)).cloned();
|
||||
match candidate {
|
||||
Some(p) if now.duration_since(*first_seen.entry(p.path.clone()).or_insert(now)) >= SETTLE => {
|
||||
log::info!("connecting to {} ({})", p.name, p.path);
|
||||
match proxy(&conn, &p.path, P2P_PEER).await?.call_method("Connect", &()).await {
|
||||
Ok(_) => Some(p),
|
||||
Err(e) => {
|
||||
log::warn!("connect {}: {e}", p.name);
|
||||
backoff.insert(p.path.clone(), now + Duration::from_secs(60));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(peer) = target else { continue };
|
||||
|
||||
// Wait for the peer's IP (DHCP on the P2P link).
|
||||
let mut ip = peer.ip.clone();
|
||||
for _ in 0..30 {
|
||||
if ip.is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
ip = objects(&conn).await.ok().and_then(|o| peers(&o).into_iter().find(|p| p.path == peer.path)?.ip);
|
||||
}
|
||||
match ip {
|
||||
Some(ip) => {
|
||||
if let Err(e) = session(&ip, peer.port, &peer.name).await {
|
||||
log::warn!("session with {}: {e:#}", peer.name);
|
||||
}
|
||||
}
|
||||
None => log::warn!("{}: no IP address on the P2P link", peer.name),
|
||||
}
|
||||
event("ended");
|
||||
if let Ok(p) = proxy(&conn, &peer.path, P2P_PEER).await {
|
||||
let _ = p.call_method("Disconnect", &()).await;
|
||||
}
|
||||
backoff.insert(peer.path.clone(), Instant::now() + Duration::from_secs(10));
|
||||
// iwd stops discovery while connected; ask again.
|
||||
if let Ok(d) = proxy(&conn, &device, P2P_DEVICE).await {
|
||||
let _ = d.call_method("RequestDiscovery", &()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn setup(conn: &Connection, device: &str, name: &str) -> Result<()> {
|
||||
let dev = proxy(conn, device, P2P_DEVICE).await?;
|
||||
dev.set_property("Name", name).await.context("setting the P2P name")?;
|
||||
dev.set_property("Enabled", true).await.context("enabling P2P")?;
|
||||
let mut props: HashMap<&str, Value> = HashMap::new();
|
||||
props.insert("Source", Value::from(false));
|
||||
props.insert("Sink", Value::from(true));
|
||||
props.insert("Port", Value::from(SOURCE_PORT));
|
||||
props.insert("HasAudio", Value::from(true));
|
||||
let sm = proxy(conn, "/net/connman/iwd", SERVICE_MANAGER).await?;
|
||||
if let Err(e) = sm.call_method("RegisterDisplayService", &(props,)).await {
|
||||
// Already registered by an earlier run of this connection is fine.
|
||||
if !e.to_string().contains("AlreadyExists") {
|
||||
bail!("RegisterDisplayService: {e}");
|
||||
}
|
||||
}
|
||||
// Discovery also keeps us visible to phones.
|
||||
dev.call_method("RequestDiscovery", &()).await.context("RequestDiscovery")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One WFD session: RTSP with the phone, the player while streaming.
|
||||
async fn session(ip: &str, port: u16, name: &str) -> Result<()> {
|
||||
log::info!("rtsp: connecting to {ip}:{port}");
|
||||
let mut stream = None;
|
||||
for _ in 0..20 {
|
||||
match TcpStream::connect((ip, port)).await {
|
||||
Ok(s) => {
|
||||
stream = Some(s);
|
||||
break;
|
||||
}
|
||||
Err(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||
}
|
||||
}
|
||||
let mut stream = stream.context("the phone's RTSP server did not answer")?;
|
||||
let mut sink = Sink::new(RTP_PORT);
|
||||
let mut player: Option<tokio::process::Child> = None;
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let result = loop {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let read = tokio::select! {
|
||||
r = tokio::time::timeout(Duration::from_secs(75), stream.read(&mut chunk)) => r,
|
||||
status = async { match player.as_mut() { Some(p) => p.wait().await, None => std::future::pending().await } } => {
|
||||
log::warn!("player exited: {status:?}");
|
||||
break Ok(());
|
||||
}
|
||||
};
|
||||
let n = match read {
|
||||
Ok(Ok(0)) => break Ok(()),
|
||||
Ok(Ok(n)) => n,
|
||||
Ok(Err(e)) => break Err(e.into()),
|
||||
Err(_) => break Err(anyhow::anyhow!("no keep-alive from the phone")),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
let mut teardown = false;
|
||||
while let Some((msg, used)) = Message::parse(&buf) {
|
||||
buf.drain(..used);
|
||||
log::debug!("rtsp <- {:?}", msg.start);
|
||||
let (out, events) = sink.handle(&msg);
|
||||
for m in out {
|
||||
log::debug!("rtsp -> {:?}", m.start);
|
||||
stream.write_all(&m.to_bytes()).await?;
|
||||
}
|
||||
for ev in events {
|
||||
match ev {
|
||||
Event::Playing if player.is_none() => {
|
||||
player = Some(start_player()?);
|
||||
event(&format!("connected {name}"));
|
||||
}
|
||||
Event::Teardown => teardown = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if teardown {
|
||||
break Ok(());
|
||||
}
|
||||
};
|
||||
if let Some(mut p) = player {
|
||||
let _ = p.kill().await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// MPEG-TS over RTP on RTP_PORT, decoded by whatever GStreamer finds best
|
||||
/// (VA-API on the N100), full screen on Wayland.
|
||||
fn start_player() -> Result<tokio::process::Child> {
|
||||
let caps = "application/x-rtp,media=video,clock-rate=90000,encoding-name=MP2T";
|
||||
let pipeline = format!(
|
||||
"udpsrc port={RTP_PORT} caps=\"{caps}\" ! rtpjitterbuffer latency=120 ! rtpmp2tdepay ! decodebin3 name=d \
|
||||
d. ! queue ! waylandsink fullscreen=true sync=false \
|
||||
d. ! queue ! audioconvert ! audioresample ! autoaudiosink sync=false"
|
||||
);
|
||||
log::info!("player: gst-launch-1.0 {pipeline}");
|
||||
let mut std_cmd = std::process::Command::new("sh");
|
||||
std_cmd.arg("-c").arg(format!("exec gst-launch-1.0 -q {pipeline}"));
|
||||
// Dies with us, so no stray player keeps the RTP port.
|
||||
// SAFETY: prctl is async-signal-safe.
|
||||
unsafe {
|
||||
use std::os::unix::process::CommandExt;
|
||||
std_cmd.pre_exec(|| {
|
||||
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut cmd = tokio::process::Command::from(std_cmd);
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::null()).kill_on_drop(true);
|
||||
cmd.spawn().context("starting gst-launch-1.0 (gstreamer1.0-tools)")
|
||||
}
|
||||
42
crates/sf-miracast/src/main.rs
Normal file
42
crates/sf-miracast/src/main.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
//! sf-miracast: experimental Miracast (Wi-Fi Display) sink.
|
||||
//!
|
||||
//! 1. Registers the TV as a Wi-Fi Display sink with iwd and keeps P2P
|
||||
//! discovery on, so phones list "Fennec OS" under Smart View / Cast screen.
|
||||
//! 2. iwd doesn't accept incoming P2P connections; it answers "try later"
|
||||
//! and the phone waits for us to connect. So when a phone that is looking
|
||||
//! for a screen (a WFD source peer) shows up, we connect to it.
|
||||
//! 3. Over the P2P link we talk WFD RTSP with the phone (`rtsp`) and play
|
||||
//! the MPEG-TS/RTP stream with GStreamer (`gst-launch-1.0`, VA-API).
|
||||
//!
|
||||
//! sf-core reads `SF-EVENT connected <name>` / `SF-EVENT ended` from stdout.
|
||||
|
||||
mod rtsp;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
// zbus logs every D-Bus handshake at info level; keep that out of the session log.
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
|
||||
.filter_module("zbus", log::LevelFilter::Warn)
|
||||
.filter_module("tracing", log::LevelFilter::Warn)
|
||||
.init();
|
||||
let mut name = "Fennec OS".to_string();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--name" => name = args.next().unwrap_or(name),
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
linux::run(name)
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = name;
|
||||
anyhow::bail!("sf-miracast needs Linux (iwd + GStreamer)")
|
||||
}
|
||||
}
|
||||
296
crates/sf-miracast/src/rtsp.rs
Normal file
296
crates/sf-miracast/src/rtsp.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
//! Wi-Fi Display (Miracast) RTSP, sink side. The phone (source) runs the
|
||||
//! RTSP server; we connect and answer its capability questions (M1–M4), it
|
||||
//! triggers SETUP/PLAY (M5–M7), keeps the session alive (M16) and finally
|
||||
//! asks for TEARDOWN. The stream itself is MPEG-TS over RTP to `rtp_port`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Default WFD RTSP port of the source.
|
||||
pub const SOURCE_PORT: u16 = 7236;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Start {
|
||||
Request { method: String, uri: String },
|
||||
Response { status: u16 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Message {
|
||||
pub start: Start,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn request(method: &str, uri: &str, cseq: u32) -> Self {
|
||||
Message {
|
||||
start: Start::Request { method: method.into(), uri: uri.into() },
|
||||
headers: vec![("CSeq".into(), cseq.to_string())],
|
||||
body: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn response(status: u16, cseq: &str) -> Self {
|
||||
Message { start: Start::Response { status }, headers: vec![("CSeq".into(), cseq.into())], body: String::new() }
|
||||
}
|
||||
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
fn with(mut self, k: &str, v: impl Into<String>) -> Self {
|
||||
self.headers.push((k.into(), v.into()));
|
||||
self
|
||||
}
|
||||
|
||||
fn with_body(mut self, body: String) -> Self {
|
||||
self.body = body;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut out = match &self.start {
|
||||
Start::Request { method, uri } => format!("{method} {uri} RTSP/1.0\r\n"),
|
||||
Start::Response { status } => format!("RTSP/1.0 {status} {}\r\n", if *status == 200 { "OK" } else { "Error" }),
|
||||
};
|
||||
for (k, v) in &self.headers {
|
||||
out.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
if !self.body.is_empty() {
|
||||
out.push_str("Content-Type: text/parameters\r\n");
|
||||
out.push_str(&format!("Content-Length: {}\r\n", self.body.len()));
|
||||
}
|
||||
out.push_str("\r\n");
|
||||
out.push_str(&self.body);
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// Parses one message from the front of `buf`; returns it and the bytes used.
|
||||
pub fn parse(buf: &[u8]) -> Option<(Message, usize)> {
|
||||
let head_end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||
let head = std::str::from_utf8(&buf[..head_end]).ok()?;
|
||||
let mut lines = head.split("\r\n");
|
||||
let first = lines.next()?;
|
||||
let start = if let Some(rest) = first.strip_prefix("RTSP/1.0 ") {
|
||||
Start::Response { status: rest.split(' ').next()?.parse().ok()? }
|
||||
} else {
|
||||
let mut p = first.split(' ');
|
||||
Start::Request { method: p.next()?.to_string(), uri: p.next()?.to_string() }
|
||||
};
|
||||
let headers: Vec<(String, String)> = lines
|
||||
.filter_map(|l| l.split_once(':'))
|
||||
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
|
||||
.collect();
|
||||
let len: usize = headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
|
||||
.and_then(|(_, v)| v.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let total = head_end + 4 + len;
|
||||
if buf.len() < total {
|
||||
return None;
|
||||
}
|
||||
let body = String::from_utf8_lossy(&buf[head_end + 4..total]).into_owned();
|
||||
Some((Message { start, headers, body }, total))
|
||||
}
|
||||
}
|
||||
|
||||
/// `name: value` lines of a text/parameters body.
|
||||
pub fn parse_params(body: &str) -> Vec<(String, String)> {
|
||||
body.lines()
|
||||
.filter_map(|l| {
|
||||
let l = l.trim();
|
||||
if l.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(match l.split_once(':') {
|
||||
Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
|
||||
None => (l.to_string(), String::new()),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Event {
|
||||
/// PLAY accepted: the stream is coming.
|
||||
Playing,
|
||||
Paused,
|
||||
/// The source ended the session.
|
||||
Teardown,
|
||||
}
|
||||
|
||||
/// The sink's side of one WFD session.
|
||||
pub struct Sink {
|
||||
cseq: u32,
|
||||
pending: HashMap<u32, String>,
|
||||
rtp_port: u16,
|
||||
presentation_url: Option<String>,
|
||||
session: Option<String>,
|
||||
}
|
||||
|
||||
impl Sink {
|
||||
pub fn new(rtp_port: u16) -> Self {
|
||||
Sink { cseq: 0, pending: HashMap::new(), rtp_port, presentation_url: None, session: None }
|
||||
}
|
||||
|
||||
fn next_request(&mut self, method: &str, uri: &str) -> Message {
|
||||
self.cseq += 1;
|
||||
self.pending.insert(self.cseq, method.to_string());
|
||||
let mut m = Message::request(method, uri, self.cseq);
|
||||
if let Some(s) = &self.session {
|
||||
m = m.with("Session", s.clone());
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// What we can play. H.264 CBP/CHP up to 1080p (VA-API decodes it), AAC and LPCM audio.
|
||||
fn capability(&self, name: &str) -> String {
|
||||
match name {
|
||||
"wfd_video_formats" => "00 00 03 10 0001ffff 1fffffff 00001fff 00 0000 0000 00 none none".into(),
|
||||
"wfd_audio_codecs" => "LPCM 00000003 00, AAC 00000007 00".into(),
|
||||
"wfd_client_rtp_ports" => format!("RTP/AVP/UDP;unicast {} 0 mode=play", self.rtp_port),
|
||||
"wfd_content_protection" | "wfd_display_edid" | "wfd_coupled_sink" | "wfd_uibc_capability" => "none".into(),
|
||||
"wfd_connector_type" => "05".into(),
|
||||
"wfd_standby_resume_capability" => "none".into(),
|
||||
_ => "none".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self) -> String {
|
||||
self.presentation_url.clone().unwrap_or_else(|| "rtsp://localhost/wfd1.0/streamid=0".into())
|
||||
}
|
||||
|
||||
/// Handles one message from the source; returns what to send back and
|
||||
/// what happened.
|
||||
pub fn handle(&mut self, msg: &Message) -> (Vec<Message>, Vec<Event>) {
|
||||
let mut out = vec![];
|
||||
let mut events = vec![];
|
||||
let cseq = msg.header("CSeq").unwrap_or("0").to_string();
|
||||
match &msg.start {
|
||||
Start::Request { method, .. } => match method.as_str() {
|
||||
// M1: the source asks what we support; then we ask it (M2).
|
||||
"OPTIONS" => {
|
||||
out.push(Message::response(200, &cseq).with("Public", "org.wfa.wfd1.0, GET_PARAMETER, SET_PARAMETER"));
|
||||
out.push(self.next_request("OPTIONS", "*").with("Require", "org.wfa.wfd1.0"));
|
||||
}
|
||||
// M3 (capabilities) or M16 (keep-alive, empty body).
|
||||
"GET_PARAMETER" => {
|
||||
let body: String = parse_params(&msg.body)
|
||||
.into_iter()
|
||||
.map(|(k, _)| format!("{k}: {}\r\n", self.capability(&k)))
|
||||
.collect();
|
||||
out.push(Message::response(200, &cseq).with_body(body));
|
||||
}
|
||||
// M4 (chosen formats, presentation URL) or M5 (trigger).
|
||||
"SET_PARAMETER" => {
|
||||
out.push(Message::response(200, &cseq));
|
||||
for (k, v) in parse_params(&msg.body) {
|
||||
match k.as_str() {
|
||||
"wfd_presentation_URL" => {
|
||||
self.presentation_url = v.split_whitespace().next().map(str::to_string);
|
||||
}
|
||||
"wfd_trigger_method" => match v.as_str() {
|
||||
"SETUP" => {
|
||||
let req = self.next_request("SETUP", &self.url()).with(
|
||||
"Transport",
|
||||
format!("RTP/AVP/UDP;unicast;client_port={}", self.rtp_port),
|
||||
);
|
||||
out.push(req);
|
||||
}
|
||||
"PLAY" => out.push(self.next_request("PLAY", &self.url())),
|
||||
"PAUSE" => out.push(self.next_request("PAUSE", &self.url())),
|
||||
"TEARDOWN" => {
|
||||
out.push(self.next_request("TEARDOWN", &self.url()));
|
||||
events.push(Event::Teardown);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => out.push(Message::response(501, &cseq)),
|
||||
},
|
||||
Start::Response { status } => {
|
||||
let method = msg.header("CSeq").and_then(|c| c.parse().ok()).and_then(|c: u32| self.pending.remove(&c));
|
||||
match (method.as_deref(), *status) {
|
||||
(Some("SETUP"), 200) => {
|
||||
self.session = msg.header("Session").map(|s| s.split(';').next().unwrap_or(s).trim().to_string());
|
||||
out.push(self.next_request("PLAY", &self.url()));
|
||||
}
|
||||
(Some("PLAY"), 200) => events.push(Event::Playing),
|
||||
(Some("PAUSE"), 200) => events.push(Event::Paused),
|
||||
(Some(m), s) if s != 200 => log::warn!("rtsp: {m} failed with {s}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, events)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn req(text: &str) -> Message {
|
||||
Message::parse(text.as_bytes()).unwrap().0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_with_body() {
|
||||
let raw = b"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: 19\r\n\r\nwfd_video_formats\r\nextra";
|
||||
let (m, used) = Message::parse(raw).unwrap();
|
||||
assert_eq!(m.body, "wfd_video_formats\r\n");
|
||||
assert_eq!(used, raw.len() - 5);
|
||||
assert!(Message::parse(b"OPTIONS * RTSP/1.0\r\nCSeq: 1\r\n").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_session() {
|
||||
let mut sink = Sink::new(1028);
|
||||
// M1 -> 200 + our M2
|
||||
let (out, _) = sink.handle(&req("OPTIONS * RTSP/1.0\r\nCSeq: 1\r\nRequire: org.wfa.wfd1.0\r\n\r\n"));
|
||||
assert_eq!(out.len(), 2);
|
||||
assert!(matches!(out[1].start, Start::Request { ref method, .. } if method == "OPTIONS"));
|
||||
// M3
|
||||
let body = "wfd_video_formats\r\nwfd_client_rtp_ports\r\nwfd_audio_codecs\r\n";
|
||||
let (out, _) = sink.handle(&req(&format!(
|
||||
"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
assert!(out[0].body.contains("wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\n"));
|
||||
// M4
|
||||
let body = "wfd_presentation_URL: rtsp://192.168.49.1/wfd1.0/streamid=0 none\r\n";
|
||||
sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 3\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
// M5 SETUP trigger -> our M6
|
||||
let body = "wfd_trigger_method: SETUP\r\n";
|
||||
let (out, _) = sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 4\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
let setup = &out[1];
|
||||
assert_eq!(setup.start, Start::Request { method: "SETUP".into(), uri: "rtsp://192.168.49.1/wfd1.0/streamid=0".into() });
|
||||
let setup_cseq = setup.header("CSeq").unwrap().to_string();
|
||||
// SETUP reply -> PLAY with session
|
||||
let (out, _) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {setup_cseq}\r\nSession: 6B8B4567;timeout=30\r\n\r\n")));
|
||||
assert_eq!(out[0].header("Session"), Some("6B8B4567"));
|
||||
let play_cseq = out[0].header("CSeq").unwrap().to_string();
|
||||
let (_, ev) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {play_cseq}\r\nSession: 6B8B4567\r\n\r\n")));
|
||||
assert_eq!(ev, vec![Event::Playing]);
|
||||
// M16 keep-alive
|
||||
let (out, _) = sink.handle(&req("GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 9\r\n\r\n"));
|
||||
assert_eq!(out[0].start, Start::Response { status: 200 });
|
||||
// Teardown trigger
|
||||
let body = "wfd_trigger_method: TEARDOWN\r\n";
|
||||
let (_, ev) = sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 10\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
assert_eq!(ev, vec![Event::Teardown]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user