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, ClipboardOrigin, CodecMask, Message, SystemAction, VideoCodec, VideoConfig, |
| 18 | VideoConfigRequest, VideoPacketHeader, |
| 19 | }; |
| 20 | use wayland_android_remote::video::{ColorMatrix, DecodedFrame, Decoder, PlaneLayout}; |
| 21 | |
| 22 | use super::video_render::YuvFrame; |
| 23 | |
| 24 | /// 디코더 스레드가 쓰고 UI가 가져가는 최신 프레임 자리. UI가 느리면 이전 프레임은 덮어쓴다. |
| 25 | #[derive(Default)] |
| 26 | pub struct FrameSlot(Mutex<Option<Arc<YuvFrame>>>); |
| 27 | |
| 28 | impl FrameSlot { |
| 29 | pub fn take(&self) -> Option<Arc<YuvFrame>> { |
| 30 | self.0.lock().unwrap_or_else(|e| e.into_inner()).take() |
| 31 | } |
| 32 | |
| 33 | fn put(&self, frame: Arc<YuvFrame>) { |
| 34 | *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(frame); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /// UI에 알리는 연결 상태 변화. |
| 39 | #[derive(Debug, Clone)] |
| 40 | pub enum ConnEvent { |
| 41 | /// TLS 연결 완료. 확인 코드를 대기 화면에 표시한다. |
| 42 | Tls { confirm_code: String }, |
| 43 | /// 휴대폰 승인 대기 중. |
| 44 | AwaitingApproval { confirm_code: String }, |
| 45 | /// 인증 완료. |
| 46 | Connected { grant: AuthGrant }, |
| 47 | /// 기기가 영상 설정을 알려왔다. |
| 48 | VideoConfig(VideoConfig), |
| 49 | /// 영상 패킷 수신 누계. |
| 50 | VideoFrames(u64), |
| 51 | /// 휴대폰 클립보드가 바뀌었다 (CLIPBOARD_SYNC, origin=기기). 텍스트와 기기가 보낸 SHA-256. |
| 52 | Clipboard(String, [u8; 32]), |
| 53 | /// 연결 실패 또는 종료. 사용자에게 보여줄 문구. |
| 54 | Ended(String), |
| 55 | } |
| 56 | |
| 57 | /// UI에서 연결 작업으로 보내는 명령. |
| 58 | #[derive(Debug)] |
| 59 | pub enum ConnCommand { |
| 60 | System(SystemAction), |
| 61 | RequestVideo(VideoConfigRequest), |
| 62 | /// 터치·휠·키·텍스트 입력과 클립보드 동기화 메시지. 받은 순서대로 바로 보낸다. |
| 63 | Input(Message), |
| 64 | } |
| 65 | |
| 66 | pub type Waker = Arc<dyn Fn() + Send + Sync>; |
| 67 | |
| 68 | pub struct Connector { |
| 69 | runtime: Runtime, |
| 70 | identity: Arc<HostIdentity>, |
| 71 | known: Arc<Mutex<KnownDevices>>, |
| 72 | waker: Waker, |
| 73 | } |
| 74 | |
| 75 | /// 진행 중인 연결 하나. 버리면 연결을 끊는다. |
| 76 | pub struct ConnHandle { |
| 77 | pub events: mpsc::Receiver<ConnEvent>, |
| 78 | pub frames: Arc<FrameSlot>, |
| 79 | commands: tmpsc::UnboundedSender<ConnCommand>, |
| 80 | task: JoinHandle<()>, |
| 81 | } |
| 82 | |
| 83 | impl ConnHandle { |
| 84 | pub fn send(&self, cmd: ConnCommand) { |
| 85 | let _ = self.commands.send(cmd); |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | impl Drop for ConnHandle { |
| 90 | fn drop(&mut self) { |
| 91 | self.task.abort(); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | impl Connector { |
| 96 | pub fn new(waker: Waker) -> std::io::Result<Self> { |
| 97 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 98 | .worker_threads(2) |
| 99 | .thread_name("android-remote-net") |
| 100 | .enable_all() |
| 101 | .build()?; |
| 102 | // FFmpeg가 stderr로 내는 VA-API 탐색·손상 프레임 경고를 줄인다. |
| 103 | ffmpeg_next::util::log::set_level(ffmpeg_next::util::log::Level::Error); |
| 104 | let identity = match HostIdentity::default_path() { |
| 105 | Some(path) => HostIdentity::load_or_create(&path).unwrap_or_else(|e| { |
| 106 | log::error!( |
| 107 | "PC 키를 읽지 못해 임시 키를 씁니다 ({}): {e}", |
| 108 | path.display() |
| 109 | ); |
| 110 | HostIdentity::generate().expect("난수 생성 실패") |
| 111 | }), |
| 112 | None => HostIdentity::generate()?, |
| 113 | }; |
| 114 | Ok(Self { |
| 115 | runtime, |
| 116 | identity: Arc::new(identity), |
| 117 | known: Arc::new(Mutex::new(KnownDevices::load_default())), |
| 118 | waker, |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | /// `keep_screen_on`이 거짓이면 영상 설정을 받은 직후 휴대폰 실제 화면을 끄게 한다. |
| 123 | pub fn start( |
| 124 | &self, |
| 125 | target: SocketAddr, |
| 126 | video: VideoConfigRequest, |
| 127 | keep_screen_on: bool, |
| 128 | ) -> ConnHandle { |
| 129 | let (tx, rx) = mpsc::channel(); |
| 130 | let (cmd_tx, cmd_rx) = tmpsc::unbounded_channel(); |
| 131 | let emit = Emitter { |
| 132 | tx, |
| 133 | waker: self.waker.clone(), |
| 134 | }; |
| 135 | let frames = Arc::new(FrameSlot::default()); |
| 136 | let task = self.runtime.spawn(run( |
| 137 | target, |
| 138 | self.identity.clone(), |
| 139 | self.known.clone(), |
| 140 | SessionOptions { |
| 141 | video, |
| 142 | keep_screen_on, |
| 143 | }, |
| 144 | emit, |
| 145 | cmd_rx, |
| 146 | frames.clone(), |
| 147 | )); |
| 148 | ConnHandle { |
| 149 | events: rx, |
| 150 | frames, |
| 151 | commands: cmd_tx, |
| 152 | task, |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// 저장된 기기 지문을 지운다 (기획서 5.5 "지문 불일치" 후 재승인). |
| 157 | pub fn forget_device(&self, target: SocketAddr) { |
| 158 | let mut known = self.known.lock().unwrap_or_else(|e| e.into_inner()); |
| 159 | if let Err(e) = known.remove(target.ip()) { |
| 160 | log::warn!("기기 기록 삭제 실패: {e}"); |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | #[derive(Clone)] |
| 166 | struct Emitter { |
| 167 | tx: mpsc::Sender<ConnEvent>, |
| 168 | waker: Waker, |
| 169 | } |
| 170 | |
| 171 | impl Emitter { |
| 172 | fn emit(&self, event: ConnEvent) { |
| 173 | if self.tx.send(event).is_ok() { |
| 174 | (self.waker)(); |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /// 세션 시작 때 기기에 요청할 설정. |
| 180 | struct SessionOptions { |
| 181 | video: VideoConfigRequest, |
| 182 | /// 거짓이면 영상 설정을 받은 직후 휴대폰 실제 화면을 끄게 한다. |
| 183 | keep_screen_on: bool, |
| 184 | } |
| 185 | |
| 186 | async fn run( |
| 187 | target: SocketAddr, |
| 188 | identity: Arc<HostIdentity>, |
| 189 | known: Arc<Mutex<KnownDevices>>, |
| 190 | options: SessionOptions, |
| 191 | emit: Emitter, |
| 192 | mut commands: tmpsc::UnboundedReceiver<ConnCommand>, |
| 193 | frames: Arc<FrameSlot>, |
| 194 | ) { |
| 195 | let pinned = known |
| 196 | .lock() |
| 197 | .unwrap_or_else(|e| e.into_inner()) |
| 198 | .get(target.ip()); |
| 199 | |
| 200 | let on_event = |e: ConnectEvent| match e { |
| 201 | ConnectEvent::TlsEstablished { confirm_code, .. } => { |
| 202 | emit.emit(ConnEvent::Tls { confirm_code }); |
| 203 | } |
| 204 | ConnectEvent::AwaitingApproval { confirm_code } => { |
| 205 | emit.emit(ConnEvent::AwaitingApproval { confirm_code }); |
| 206 | } |
| 207 | }; |
| 208 | let mut session = match connect( |
| 209 | target, |
| 210 | &identity, |
| 211 | pinned, |
| 212 | ConnectOptions::default(), |
| 213 | on_event, |
| 214 | ) |
| 215 | .await |
| 216 | { |
| 217 | Ok(s) => s, |
| 218 | Err(e) => { |
| 219 | emit.emit(ConnEvent::Ended(describe_connect_error(&e))); |
| 220 | return; |
| 221 | } |
| 222 | }; |
| 223 | |
| 224 | if session.grant == AuthGrant::Always { |
| 225 | let mut known = known.lock().unwrap_or_else(|e| e.into_inner()); |
| 226 | if let Err(e) = known.insert(target.ip(), session.fingerprint) { |
| 227 | log::warn!("기기 지문 저장 실패: {e}"); |
| 228 | } |
| 229 | } |
| 230 | emit.emit(ConnEvent::Connected { |
| 231 | grant: session.grant, |
| 232 | }); |
| 233 | |
| 234 | // 영상 설정을 먼저 받아 코덱을 알아낸 뒤 영상 채널을 연다 (기획서 7.6 3~4단계). |
| 235 | let config = match request_video_config(session.control(), options.video).await { |
| 236 | Ok(cfg) => cfg, |
| 237 | Err(reason) => { |
| 238 | emit.emit(ConnEvent::Ended(reason)); |
| 239 | return; |
| 240 | } |
| 241 | }; |
| 242 | emit.emit(ConnEvent::VideoConfig(config)); |
| 243 | |
| 244 | // 세션이 시작됐으니 휴대폰 화면 설정을 적용한다. 연결이 끝나면 휴대폰이 스스로 되돌린다. |
| 245 | // 그 사이 설정 창에서 바꾼 값은 명령 대기열에 있다가 이 뒤에 나가 최종 상태가 된다. |
| 246 | let screen = if options.keep_screen_on { |
| 247 | SystemAction::ScreenOn |
| 248 | } else { |
| 249 | SystemAction::ScreenOff |
| 250 | }; |
| 251 | if let Err(e) = session.control().send(&Message::SystemAction(screen)).await { |
| 252 | emit.emit(ConnEvent::Ended(format!("연결이 끊겼습니다: {e}"))); |
| 253 | return; |
| 254 | } |
| 255 | |
| 256 | let (dec_tx, dec_rx) = mpsc::channel::<DecoderInput>(); |
| 257 | let (keyframe_tx, mut keyframe_rx) = tmpsc::unbounded_channel::<()>(); |
| 258 | let _ = dec_tx.send(DecoderInput::Codec(config.codec)); |
| 259 | let decoder_thread = { |
| 260 | let emit = emit.clone(); |
| 261 | std::thread::Builder::new() |
| 262 | .name("video-decode".to_owned()) |
| 263 | .spawn(move || decode_loop(dec_rx, frames, emit, keyframe_tx)) |
| 264 | }; |
| 265 | if let Err(e) = decoder_thread { |
| 266 | log::error!("디코더 스레드를 만들지 못했습니다: {e}"); |
| 267 | } |
| 268 | |
| 269 | let video_task = match session.open_video(Duration::from_secs(5)).await { |
| 270 | Ok(mut stream) => { |
| 271 | let dec_tx = dec_tx.clone(); |
| 272 | Some(tokio::spawn(async move { |
| 273 | while let Ok((header, data)) = stream.read_packet().await { |
| 274 | if dec_tx.send(DecoderInput::Packet(header, data)).is_err() { |
| 275 | break; |
| 276 | } |
| 277 | } |
| 278 | })) |
| 279 | } |
| 280 | Err(e) => { |
| 281 | log::warn!("영상 채널 연결 실패: {e}"); |
| 282 | None |
| 283 | } |
| 284 | }; |
| 285 | |
| 286 | let reason = control_loop( |
| 287 | session.control(), |
| 288 | &mut commands, |
| 289 | &mut keyframe_rx, |
| 290 | &dec_tx, |
| 291 | &emit, |
| 292 | ) |
| 293 | .await; |
| 294 | if let Some(t) = video_task { |
| 295 | t.abort(); |
| 296 | } |
| 297 | // dec_tx가 사라지면 디코더 스레드도 끝난다. |
| 298 | drop(dec_tx); |
| 299 | emit.emit(ConnEvent::Ended(reason)); |
| 300 | } |
| 301 | |
| 302 | /// VIDEO_CONFIG_REQUEST를 보내고 VIDEO_CONFIG 응답을 기다린다. |
| 303 | async fn request_video_config( |
| 304 | control: &mut wayland_android_remote::net::FramedStream< |
| 305 | wayland_android_remote::net::DeviceStream, |
| 306 | >, |
| 307 | request: VideoConfigRequest, |
| 308 | ) -> Result<VideoConfig, String> { |
| 309 | let lost = |e: FramedError| format!("연결이 끊겼습니다: {e}"); |
| 310 | control |
| 311 | .send(&Message::VideoConfigRequest(request)) |
| 312 | .await |
| 313 | .map_err(lost)?; |
| 314 | let wait = async { |
| 315 | loop { |
| 316 | match control.read_message().await { |
| 317 | Ok((_, Message::VideoConfig(cfg))) => return Ok(cfg), |
| 318 | Ok((seq, Message::Ping)) => { |
| 319 | control |
| 320 | .send_with_seq(&Message::Pong, seq) |
| 321 | .await |
| 322 | .map_err(lost)?; |
| 323 | } |
| 324 | Ok((_, Message::Error(e))) => { |
| 325 | return Err(format!("기기가 영상을 시작하지 못했습니다: {}", e.reason)); |
| 326 | } |
| 327 | Ok(_) => {} |
| 328 | Err(e) => return Err(lost(e)), |
| 329 | } |
| 330 | } |
| 331 | }; |
| 332 | tokio::time::timeout(Duration::from_secs(5), wait) |
| 333 | .await |
| 334 | .map_err(|_| "영상 설정 응답이 없습니다".to_owned())? |
| 335 | } |
| 336 | |
| 337 | enum DecoderInput { |
| 338 | Codec(VideoCodec), |
| 339 | Packet(VideoPacketHeader, bytes::Bytes), |
| 340 | } |
| 341 | |
| 342 | /// 디코더 스레드. 패킷마다 2~6ms 막히므로 tokio 작업자와 분리한다. |
| 343 | fn decode_loop( |
| 344 | input: mpsc::Receiver<DecoderInput>, |
| 345 | frames: Arc<FrameSlot>, |
| 346 | emit: Emitter, |
| 347 | keyframe: tmpsc::UnboundedSender<()>, |
| 348 | ) { |
| 349 | let mut decoder: Option<Decoder> = None; |
| 350 | let mut count = 0u64; |
| 351 | let mut last_keyframe_request: Option<std::time::Instant> = None; |
| 352 | // 2초마다 디코딩 fps와 평균 디코딩 시간을 남긴다. |
| 353 | let mut stats_since = std::time::Instant::now(); |
| 354 | let (mut stats_frames, mut stats_decode) = (0u32, Duration::ZERO); |
| 355 | while let Ok(msg) = input.recv() { |
| 356 | match msg { |
| 357 | DecoderInput::Codec(codec) => { |
| 358 | if decoder.as_ref().is_some_and(|d| d.codec() == codec) { |
| 359 | continue; |
| 360 | } |
| 361 | match Decoder::new(codec, true) { |
| 362 | Ok(d) => { |
| 363 | log::info!("영상 디코더: {codec:?} {}", d.backend()); |
| 364 | decoder = Some(d); |
| 365 | } |
| 366 | Err(e) => log::error!("디코더 생성 실패: {e}"), |
| 367 | } |
| 368 | } |
| 369 | DecoderInput::Packet(header, data) => { |
| 370 | let Some(d) = decoder.as_mut() else { continue }; |
| 371 | let started = std::time::Instant::now(); |
| 372 | let result = d.decode(&header, &data); |
| 373 | if !header.is_config { |
| 374 | stats_frames += 1; |
| 375 | stats_decode += started.elapsed(); |
| 376 | } |
| 377 | if stats_since.elapsed() >= Duration::from_secs(2) && stats_frames > 0 { |
| 378 | let secs = stats_since.elapsed().as_secs_f64(); |
| 379 | log::info!( |
| 380 | "영상 {:.1}fps, 평균 디코딩 {:.2}ms ({})", |
| 381 | f64::from(stats_frames) / secs, |
| 382 | stats_decode.as_secs_f64() * 1000.0 / f64::from(stats_frames), |
| 383 | d.backend() |
| 384 | ); |
| 385 | stats_since = std::time::Instant::now(); |
| 386 | (stats_frames, stats_decode) = (0, Duration::ZERO); |
| 387 | } |
| 388 | match result { |
| 389 | Ok(out) => { |
| 390 | // 한 번에 여러 프레임이 나오면 최신 것만 그린다. |
| 391 | if let Some(frame) = out.into_iter().last() { |
| 392 | count += 1; |
| 393 | frames.put(Arc::new(to_yuv(frame))); |
| 394 | emit.emit(ConnEvent::VideoFrames(count)); |
| 395 | } |
| 396 | } |
| 397 | Err(e) => { |
| 398 | log::debug!("디코딩 오류: {e}"); |
| 399 | let recent = last_keyframe_request |
| 400 | .is_some_and(|t| t.elapsed() < Duration::from_millis(500)); |
| 401 | if e.needs_keyframe() && !recent { |
| 402 | last_keyframe_request = Some(std::time::Instant::now()); |
| 403 | let _ = keyframe.send(()); |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | fn to_yuv(frame: DecodedFrame) -> YuvFrame { |
| 413 | YuvFrame { |
| 414 | width: frame.width, |
| 415 | height: frame.height, |
| 416 | nv12: matches!(frame.layout, PlaneLayout::Nv12), |
| 417 | planes: frame |
| 418 | .planes |
| 419 | .into_iter() |
| 420 | .map(|p| (p.data, p.stride, p.width, p.height)) |
| 421 | .collect(), |
| 422 | bt709: matches!(frame.color.matrix, ColorMatrix::Bt709), |
| 423 | full_range: frame.color.full_range, |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | async fn control_loop( |
| 428 | control: &mut wayland_android_remote::net::FramedStream< |
| 429 | wayland_android_remote::net::DeviceStream, |
| 430 | >, |
| 431 | commands: &mut tmpsc::UnboundedReceiver<ConnCommand>, |
| 432 | keyframe: &mut tmpsc::UnboundedReceiver<()>, |
| 433 | decoder: &mpsc::Sender<DecoderInput>, |
| 434 | emit: &Emitter, |
| 435 | ) -> String { |
| 436 | let mut ping = tokio::time::interval(Duration::from_secs(2)); |
| 437 | loop { |
| 438 | tokio::select! { |
| 439 | msg = control.read_message() => match msg { |
| 440 | Ok((seq, Message::Ping)) => { |
| 441 | if let Err(e) = control.send_with_seq(&Message::Pong, seq).await { |
| 442 | return format!("연결이 끊겼습니다: {e}"); |
| 443 | } |
| 444 | } |
| 445 | Ok((_, Message::VideoConfig(cfg))) => { |
| 446 | let _ = decoder.send(DecoderInput::Codec(cfg.codec)); |
| 447 | emit.emit(ConnEvent::VideoConfig(cfg)); |
| 448 | } |
| 449 | Ok((_, Message::ClipboardSync(c))) => { |
| 450 | if c.origin == ClipboardOrigin::AndroidDevice { |
| 451 | emit.emit(ConnEvent::Clipboard(c.text, c.sha256)); |
| 452 | } else { |
| 453 | log::debug!("기기가 호스트 출처 클립보드를 보냈습니다. 무시합니다"); |
| 454 | } |
| 455 | } |
| 456 | Ok((_, Message::Error(e))) => log::warn!("기기 오류: {:#06x} {}", e.code, e.reason), |
| 457 | Ok((_, other)) => log::debug!("처리하지 않은 메시지: {:?}", other.msg_type()), |
| 458 | Err(FramedError::Closed) => return "기기가 연결을 닫았습니다".to_owned(), |
| 459 | Err(e) => return format!("연결이 끊겼습니다: {e}"), |
| 460 | }, |
| 461 | cmd = commands.recv() => { |
| 462 | let msg = match cmd { |
| 463 | Some(ConnCommand::System(a)) => Message::SystemAction(a), |
| 464 | Some(ConnCommand::RequestVideo(r)) => Message::VideoConfigRequest(r), |
| 465 | Some(ConnCommand::Input(m)) => m, |
| 466 | None => return "연결을 끊었습니다".to_owned(), |
| 467 | }; |
| 468 | if let Err(e) = control.send(&msg).await { |
| 469 | return format!("연결이 끊겼습니다: {e}"); |
| 470 | } |
| 471 | } |
| 472 | Some(()) = keyframe.recv() => { |
| 473 | if let Err(e) = control.send(&Message::VideoRequestKeyframe).await { |
| 474 | return format!("연결이 끊겼습니다: {e}"); |
| 475 | } |
| 476 | } |
| 477 | _ = ping.tick() => { |
| 478 | if let Err(e) = control.send(&Message::Ping).await { |
| 479 | return format!("연결이 끊겼습니다: {e}"); |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | fn describe_connect_error(e: &ConnectError) -> String { |
| 487 | match e { |
| 488 | ConnectError::Io(io) if io.kind() == std::io::ErrorKind::ConnectionRefused => { |
| 489 | "휴대폰에서 Android Remote 앱을 열어 서비스를 켜 주세요".to_owned() |
| 490 | } |
| 491 | ConnectError::Timeout("연결") => "기기에 연결할 수 없습니다 (시간 초과)".to_owned(), |
| 492 | other => other.to_string(), |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | /// 사이드 메뉴 설정을 영상 설정 요청으로 바꾼다. |
| 497 | pub fn video_request(max_size: u16, max_fps: u8, bitrate_mbps: u32) -> VideoConfigRequest { |
| 498 | VideoConfigRequest { |
| 499 | max_size, |
| 500 | max_fps, |
| 501 | // 호스트는 NVDEC/VA-API로 세 코덱 모두 하드웨어 디코딩할 수 있다고 가정한다. |
| 502 | // 디코더를 붙일 때 실제 지원 여부로 바꾼다. |
| 503 | codecs: CodecMask::H264 | CodecMask::H265 | CodecMask::AV1, |
| 504 | bitrate: bitrate_mbps * 1_000_000, |
| 505 | } |
| 506 | } |