//! 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; type Objects = HashMap>; 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 { p.get(k).and_then(|v| bool::try_from(v.try_clone().ok()?).ok()) } fn get_str(p: &Props, k: &str) -> Option { p.get(k).and_then(|v| String::try_from(v.try_clone().ok()?).ok()) } fn get_u16(p: &Props, k: &str) -> Option { p.get(k).and_then(|v| u16::try_from(v.try_clone().ok()?).ok()) } async fn objects(conn: &Connection) -> Result { 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> { Ok(zbus::Proxy::new(conn, IWD, path, iface).await?) } #[derive(Debug, Clone)] struct Peer { path: String, name: String, connected: bool, ip: Option, source: bool, port: u16, } fn peers(objs: &Objects) -> Vec { 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 = None; let mut warned = false; let mut first_seen: HashMap = HashMap::new(); let mut backoff: HashMap = 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 = 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 = None; let mut buf: Vec = 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 { 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)") }