leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! GUI와 네트워크 계층 사이의 연결 관리. 네트워크 작업은 tokio 런타임에서 돌고, |
| 2 | //! 결과는 채널로 UI 스레드에 전달한 뒤 이벤트 루프를 깨운다. |
| 3 | |
| 4 | use std::net::SocketAddr; |
| 5 | use std::sync::mpsc; |
| 6 | use std::sync::{Arc, Mutex}; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use tokio::runtime::Runtime; |
| 10 | use tokio::sync::mpsc as tmpsc; |
| 11 | use tokio::task::JoinHandle; |
| 12 | |
| 13 | use wayland_android_remote::net::{ |
| 14 | ConnectError, ConnectEvent, ConnectOptions, FramedError, HostIdentity, KnownDevices, connect, |
| 15 | }; |
| 16 | use wayland_android_remote::protocol::{ |
| 17 | AuthGrant, CodecMask, Message, SystemAction, VideoConfig, VideoConfigRequest, |
| 18 | }; |
| 19 | |
| 20 | /// UI에 알리는 연결 상태 변화. |
| 21 | #[derive(Debug, Clone)] |
| 22 | pub enum ConnEvent { |
| 23 | /// TLS 연결 완료. 확인 코드를 대기 화면에 표시한다. |
| 24 | Tls { confirm_code: String }, |
| 25 | /// 휴대폰 승인 대기 중. |
| 26 | AwaitingApproval { confirm_code: String }, |
| 27 | /// 인증 완료. |
| 28 | Connected { grant: AuthGrant }, |
| 29 | /// 기기가 영상 설정을 알려왔다. |
| 30 | VideoConfig(VideoConfig), |
| 31 | /// 영상 패킷 수신 누계. |
| 32 | VideoFrames(u64), |
| 33 | /// 연결 실패 또는 종료. 사용자에게 보여줄 문구. |
| 34 | Ended(String), |
| 35 | } |
| 36 | |
| 37 | /// UI에서 연결 작업으로 보내는 명령. |
| 38 | #[derive(Debug)] |
| 39 | pub enum ConnCommand { |
| 40 | System(SystemAction), |
| 41 | RequestVideo(VideoConfigRequest), |
| 42 | } |
| 43 | |
| 44 | pub type Waker = Arc<dyn Fn() + Send + Sync>; |
| 45 | |
| 46 | pub struct Connector { |
| 47 | runtime: Runtime, |
| 48 | identity: Arc<HostIdentity>, |
| 49 | known: Arc<Mutex<KnownDevices>>, |
| 50 | waker: Waker, |
| 51 | } |
| 52 | |
| 53 | /// 진행 중인 연결 하나. 버리면 연결을 끊는다. |
| 54 | pub struct ConnHandle { |
| 55 | pub events: mpsc::Receiver<ConnEvent>, |
| 56 | commands: tmpsc::UnboundedSender<ConnCommand>, |
| 57 | task: JoinHandle<()>, |
| 58 | } |
| 59 | |
| 60 | impl ConnHandle { |
| 61 | pub fn send(&self, cmd: ConnCommand) { |
| 62 | let _ = self.commands.send(cmd); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl Drop for ConnHandle { |
| 67 | fn drop(&mut self) { |
| 68 | self.task.abort(); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | impl Connector { |
| 73 | pub fn new(waker: Waker) -> std::io::Result<Self> { |
| 74 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 75 | .worker_threads(2) |
| 76 | .thread_name("android-remote-net") |
| 77 | .enable_all() |
| 78 | .build()?; |
| 79 | let identity = match HostIdentity::default_path() { |
| 80 | Some(path) => HostIdentity::load_or_create(&path).unwrap_or_else(|e| { |
| 81 | log::error!( |
| 82 | "PC 키를 읽지 못해 임시 키를 씁니다 ({}): {e}", |
| 83 | path.display() |
| 84 | ); |
| 85 | HostIdentity::generate().expect("난수 생성 실패") |
| 86 | }), |
| 87 | None => HostIdentity::generate()?, |
| 88 | }; |
| 89 | Ok(Self { |
| 90 | runtime, |
| 91 | identity: Arc::new(identity), |
| 92 | known: Arc::new(Mutex::new(KnownDevices::load_default())), |
| 93 | waker, |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | pub fn start(&self, target: SocketAddr, video: VideoConfigRequest) -> ConnHandle { |
| 98 | let (tx, rx) = mpsc::channel(); |
| 99 | let (cmd_tx, cmd_rx) = tmpsc::unbounded_channel(); |
| 100 | let emit = Emitter { |
| 101 | tx, |
| 102 | waker: self.waker.clone(), |
| 103 | }; |
| 104 | let task = self.runtime.spawn(run( |
| 105 | target, |
| 106 | self.identity.clone(), |
| 107 | self.known.clone(), |
| 108 | video, |
| 109 | emit, |
| 110 | cmd_rx, |
| 111 | )); |
| 112 | ConnHandle { |
| 113 | events: rx, |
| 114 | commands: cmd_tx, |
| 115 | task, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// 저장된 기기 지문을 지운다 (기획서 5.5 "지문 불일치" 후 재승인). |
| 120 | pub fn forget_device(&self, target: SocketAddr) { |
| 121 | let mut known = self.known.lock().unwrap_or_else(|e| e.into_inner()); |
| 122 | if let Err(e) = known.remove(target.ip()) { |
| 123 | log::warn!("기기 기록 삭제 실패: {e}"); |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | #[derive(Clone)] |
| 129 | struct Emitter { |
| 130 | tx: mpsc::Sender<ConnEvent>, |
| 131 | waker: Waker, |
| 132 | } |
| 133 | |
| 134 | impl Emitter { |
| 135 | fn emit(&self, event: ConnEvent) { |
| 136 | if self.tx.send(event).is_ok() { |
| 137 | (self.waker)(); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | async fn run( |
| 143 | target: SocketAddr, |
| 144 | identity: Arc<HostIdentity>, |
| 145 | known: Arc<Mutex<KnownDevices>>, |
| 146 | video: VideoConfigRequest, |
| 147 | emit: Emitter, |
| 148 | mut commands: tmpsc::UnboundedReceiver<ConnCommand>, |
| 149 | ) { |
| 150 | let pinned = known |
| 151 | .lock() |
| 152 | .unwrap_or_else(|e| e.into_inner()) |
| 153 | .get(target.ip()); |
| 154 | |
| 155 | let on_event = |e: ConnectEvent| match e { |
| 156 | ConnectEvent::TlsEstablished { confirm_code, .. } => { |
| 157 | emit.emit(ConnEvent::Tls { confirm_code }); |
| 158 | } |
| 159 | ConnectEvent::AwaitingApproval { confirm_code } => { |
| 160 | emit.emit(ConnEvent::AwaitingApproval { confirm_code }); |
| 161 | } |
| 162 | }; |
| 163 | let mut session = match connect( |
| 164 | target, |
| 165 | &identity, |
| 166 | pinned, |
| 167 | ConnectOptions::default(), |
| 168 | on_event, |
| 169 | ) |
| 170 | .await |
| 171 | { |
| 172 | Ok(s) => s, |
| 173 | Err(e) => { |
| 174 | emit.emit(ConnEvent::Ended(describe_connect_error(&e))); |
| 175 | return; |
| 176 | } |
| 177 | }; |
| 178 | |
| 179 | if session.grant == AuthGrant::Always { |
| 180 | let mut known = known.lock().unwrap_or_else(|e| e.into_inner()); |
| 181 | if let Err(e) = known.insert(target.ip(), session.fingerprint) { |
| 182 | log::warn!("기기 지문 저장 실패: {e}"); |
| 183 | } |
| 184 | } |
| 185 | emit.emit(ConnEvent::Connected { |
| 186 | grant: session.grant, |
| 187 | }); |
| 188 | |
| 189 | if let Err(e) = session |
| 190 | .control() |
| 191 | .send(&Message::VideoConfigRequest(video)) |
| 192 | .await |
| 193 | { |
| 194 | emit.emit(ConnEvent::Ended(format!("연결이 끊겼습니다: {e}"))); |
| 195 | return; |
| 196 | } |
| 197 | |
| 198 | // 영상 채널: 디코더가 붙기 전까지는 수신 프레임 수만 센다. |
| 199 | let video_task = match session.open_video(Duration::from_secs(5)).await { |
| 200 | Ok(mut stream) => { |
| 201 | let emit = emit.clone(); |
| 202 | Some(tokio::spawn(async move { |
| 203 | let mut frames = 0u64; |
| 204 | while let Ok((header, _data)) = stream.read_packet().await { |
| 205 | if !header.is_config { |
| 206 | frames += 1; |
| 207 | emit.emit(ConnEvent::VideoFrames(frames)); |
| 208 | } |
| 209 | } |
| 210 | })) |
| 211 | } |
| 212 | Err(e) => { |
| 213 | log::warn!("영상 채널 연결 실패: {e}"); |
| 214 | None |
| 215 | } |
| 216 | }; |
| 217 | |
| 218 | let reason = control_loop(session.control(), &mut commands, &emit).await; |
| 219 | if let Some(t) = video_task { |
| 220 | t.abort(); |
| 221 | } |
| 222 | emit.emit(ConnEvent::Ended(reason)); |
| 223 | } |
| 224 | |
| 225 | async fn control_loop( |
| 226 | control: &mut wayland_android_remote::net::FramedStream< |
| 227 | wayland_android_remote::net::DeviceStream, |
| 228 | >, |
| 229 | commands: &mut tmpsc::UnboundedReceiver<ConnCommand>, |
| 230 | emit: &Emitter, |
| 231 | ) -> String { |
| 232 | let mut ping = tokio::time::interval(Duration::from_secs(2)); |
| 233 | loop { |
| 234 | tokio::select! { |
| 235 | msg = control.read_message() => match msg { |
| 236 | Ok((seq, Message::Ping)) => { |
| 237 | if let Err(e) = control.send_with_seq(&Message::Pong, seq).await { |
| 238 | return format!("연결이 끊겼습니다: {e}"); |
| 239 | } |
| 240 | } |
| 241 | Ok((_, Message::VideoConfig(cfg))) => emit.emit(ConnEvent::VideoConfig(cfg)), |
| 242 | Ok((_, Message::Error(e))) => log::warn!("기기 오류: {:#06x} {}", e.code, e.reason), |
| 243 | Ok((_, other)) => log::debug!("처리하지 않은 메시지: {:?}", other.msg_type()), |
| 244 | Err(FramedError::Closed) => return "기기가 연결을 닫았습니다".to_owned(), |
| 245 | Err(e) => return format!("연결이 끊겼습니다: {e}"), |
| 246 | }, |
| 247 | cmd = commands.recv() => { |
| 248 | let msg = match cmd { |
| 249 | Some(ConnCommand::System(a)) => Message::SystemAction(a), |
| 250 | Some(ConnCommand::RequestVideo(r)) => Message::VideoConfigRequest(r), |
| 251 | None => return "연결을 끊었습니다".to_owned(), |
| 252 | }; |
| 253 | if let Err(e) = control.send(&msg).await { |
| 254 | return format!("연결이 끊겼습니다: {e}"); |
| 255 | } |
| 256 | } |
| 257 | _ = ping.tick() => { |
| 258 | if let Err(e) = control.send(&Message::Ping).await { |
| 259 | return format!("연결이 끊겼습니다: {e}"); |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn describe_connect_error(e: &ConnectError) -> String { |
| 267 | match e { |
| 268 | ConnectError::Io(io) if io.kind() == std::io::ErrorKind::ConnectionRefused => { |
| 269 | "휴대폰에서 Android Remote 앱을 열어 서비스를 켜 주세요".to_owned() |
| 270 | } |
| 271 | ConnectError::Timeout("연결") => "기기에 연결할 수 없습니다 (시간 초과)".to_owned(), |
| 272 | other => other.to_string(), |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// 사이드 메뉴 설정을 영상 설정 요청으로 바꾼다. |
| 277 | pub fn video_request(max_size: u16, max_fps: u8, bitrate_mbps: u32) -> VideoConfigRequest { |
| 278 | VideoConfigRequest { |
| 279 | max_size, |
| 280 | max_fps, |
| 281 | // 호스트는 NVDEC/VA-API로 세 코덱 모두 하드웨어 디코딩할 수 있다고 가정한다. |
| 282 | // 디코더를 붙일 때 실제 지원 여부로 바꾼다. |
| 283 | codecs: CodecMask::H264 | CodecMask::H265 | CodecMask::AV1, |
| 284 | bitrate: bitrate_mbps * 1_000_000, |
| 285 | } |
| 286 | } |