leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! GUI와 네트워크 계층 사이의 연결 관리. 네트워크 작업은 tokio 런타임에서 돌고, |
| 2 | //! 결과는 채널로 UI 스레드에 전달한 뒤 이벤트 루프를 깨운다. |
| 3 | |
| 4 | use std::net::SocketAddr; |
| 5 | |
| 6 | use wayland_android_remote::adb::{AdbError, prepare_usb}; |
| 7 | |
| 8 | use super::recent::is_usb; |
| 9 | use std::sync::mpsc; |
| 10 | use std::sync::{Arc, Mutex}; |
| 11 | use std::time::Duration; |
| 12 | |
| 13 | use tokio::runtime::Runtime; |
| 14 | use tokio::sync::mpsc as tmpsc; |
| 15 | use tokio::task::JoinHandle; |
| 16 | |
| 17 | use wayland_android_remote::net::{ |
| 18 | ConnectError, ConnectEvent, ConnectOptions, FramedError, HostIdentity, KnownDevices, connect, |
| 19 | }; |
| 20 | use wayland_android_remote::protocol::{ |
| 21 | AuthGrant, ClipboardContent, ClipboardOrigin, CodecMask, Message, SystemAction, VideoCodec, |
| 22 | VideoConfig, VideoConfigRequest, VideoPacketHeader, error_code, |
| 23 | }; |
| 24 | use wayland_android_remote::video::{ColorMatrix, DecodedFrame, Decoder, PlaneLayout}; |
| 25 | |
| 26 | use super::transfer; |
| 27 | use super::video_render::YuvFrame; |
| 28 | |
| 29 | /// 디코더 스레드가 쓰고 UI가 가져가는 최신 프레임 자리. UI가 느리면 이전 프레임은 덮어쓴다. |
| 30 | #[derive(Default)] |
| 31 | pub struct FrameSlot(Mutex<Option<Arc<YuvFrame>>>); |
| 32 | |
| 33 | impl FrameSlot { |
| 34 | pub fn take(&self) -> Option<Arc<YuvFrame>> { |
| 35 | self.0.lock().unwrap_or_else(|e| e.into_inner()).take() |
| 36 | } |
| 37 | |
| 38 | fn put(&self, frame: Arc<YuvFrame>) { |
| 39 | *self.0.lock().unwrap_or_else(|e| e.into_inner()) = Some(frame); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// UI에 알리는 연결 상태 변화. |
| 44 | #[derive(Debug, Clone)] |
| 45 | pub enum ConnEvent { |
| 46 | /// TLS 연결 완료. 확인 코드를 대기 화면에 표시한다. |
| 47 | Tls { confirm_code: String }, |
| 48 | /// 휴대폰 승인 대기 중. |
| 49 | AwaitingApproval { confirm_code: String }, |
| 50 | /// 인증 완료. |
| 51 | Connected { grant: AuthGrant }, |
| 52 | /// 기기가 영상 설정을 알려왔다. |
| 53 | VideoConfig(VideoConfig), |
| 54 | /// 영상 패킷 수신 누계. |
| 55 | VideoFrames(u64), |
| 56 | /// 휴대폰 클립보드가 바뀌었다 (CLIPBOARD_SYNC, origin=기기). 내용과 기기가 보낸 SHA-256. |
| 57 | Clipboard(ClipboardContent, [u8; 32]), |
| 58 | /// 파일 전송 진행·완료 알림. |
| 59 | Transfer(transfer::Notice), |
| 60 | /// 연결 실패 또는 종료. `reason`은 사용자에게 보여줄 문구. |
| 61 | /// `retry`는 네트워크 문제로 끊겨 같은 주소로 다시 연결해 볼 만한지. 인증 실패·지문 불일치· |
| 62 | /// 거부는 거짓이다. 사용자가 끊은 경우는 핸들을 버리므로 이 이벤트가 오지 않는다. |
| 63 | Ended { reason: String, retry: bool }, |
| 64 | } |
| 65 | |
| 66 | /// UI에서 연결 작업으로 보내는 명령. |
| 67 | #[derive(Debug)] |
| 68 | pub enum ConnCommand { |
| 69 | System(SystemAction), |
| 70 | RequestVideo(VideoConfigRequest), |
| 71 | /// 터치·휠·키·텍스트 입력과 클립보드 동기화 메시지. 받은 순서대로 바로 보낸다. |
| 72 | Input(Message), |
| 73 | /// 휴대폰으로 보낼 파일. 다른 메시지가 없을 때 조금씩 보낸다. |
| 74 | SendFiles(Vec<std::path::PathBuf>), |
| 75 | } |
| 76 | |
| 77 | pub type Waker = Arc<dyn Fn() + Send + Sync>; |
| 78 | |
| 79 | pub struct Connector { |
| 80 | runtime: Runtime, |
| 81 | identity: Arc<HostIdentity>, |
| 82 | known: Arc<Mutex<KnownDevices>>, |
| 83 | waker: Waker, |
| 84 | } |
| 85 | |
| 86 | /// 진행 중인 연결 하나. 버리면 연결을 끊는다. |
| 87 | pub struct ConnHandle { |
| 88 | pub events: mpsc::Receiver<ConnEvent>, |
| 89 | pub frames: Arc<FrameSlot>, |
| 90 | commands: tmpsc::UnboundedSender<ConnCommand>, |
| 91 | task: JoinHandle<()>, |
| 92 | } |
| 93 | |
| 94 | impl ConnHandle { |
| 95 | pub fn send(&self, cmd: ConnCommand) { |
| 96 | let _ = self.commands.send(cmd); |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | impl Drop for ConnHandle { |
| 101 | fn drop(&mut self) { |
| 102 | self.task.abort(); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | impl Connector { |
| 107 | pub fn new(waker: Waker) -> std::io::Result<Self> { |
| 108 | let runtime = tokio::runtime::Builder::new_multi_thread() |
| 109 | .worker_threads(2) |
| 110 | .thread_name("android-remote-net") |
| 111 | .enable_all() |
| 112 | .build()?; |
| 113 | // FFmpeg가 stderr로 내는 VA-API 탐색·손상 프레임 경고를 줄인다. |
| 114 | ffmpeg_next::util::log::set_level(ffmpeg_next::util::log::Level::Error); |
| 115 | let identity = match HostIdentity::default_path() { |
| 116 | Some(path) => HostIdentity::load_or_create(&path).unwrap_or_else(|e| { |
| 117 | log::error!( |
| 118 | "PC 키를 읽지 못해 임시 키를 씁니다 ({}): {e}", |
| 119 | path.display() |
| 120 | ); |
| 121 | HostIdentity::generate().expect("난수 생성 실패") |
| 122 | }), |
| 123 | None => HostIdentity::generate()?, |
| 124 | }; |
| 125 | Ok(Self { |
| 126 | runtime, |
| 127 | identity: Arc::new(identity), |
| 128 | known: Arc::new(Mutex::new(KnownDevices::load_default())), |
| 129 | waker, |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | /// `keep_screen_on`이 거짓이면 영상 설정을 받은 직후 휴대폰 실제 화면을 끄게 한다. |
| 134 | pub fn start( |
| 135 | &self, |
| 136 | target: SocketAddr, |
| 137 | video: VideoConfigRequest, |
| 138 | keep_screen_on: bool, |
| 139 | ) -> ConnHandle { |
| 140 | let (tx, rx) = mpsc::channel(); |
| 141 | let (cmd_tx, cmd_rx) = tmpsc::unbounded_channel(); |
| 142 | let emit = Emitter { |
| 143 | tx, |
| 144 | waker: self.waker.clone(), |
| 145 | }; |
| 146 | let frames = Arc::new(FrameSlot::default()); |
| 147 | let task = self.runtime.spawn(run( |
| 148 | target, |
| 149 | self.identity.clone(), |
| 150 | self.known.clone(), |
| 151 | SessionOptions { |
| 152 | video, |
| 153 | keep_screen_on, |
| 154 | }, |
| 155 | emit, |
| 156 | cmd_rx, |
| 157 | frames.clone(), |
| 158 | )); |
| 159 | ConnHandle { |
| 160 | events: rx, |
| 161 | frames, |
| 162 | commands: cmd_tx, |
| 163 | task, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// 저장된 기기 지문을 지운다 (기획서 5.5 "지문 불일치" 후 재승인). |
| 168 | pub fn forget_device(&self, target: SocketAddr) { |
| 169 | let ip = if is_usb(target) { |
| 170 | std::net::Ipv4Addr::LOCALHOST.into() |
| 171 | } else { |
| 172 | target.ip() |
| 173 | }; |
| 174 | let mut known = self.known.lock().unwrap_or_else(|e| e.into_inner()); |
| 175 | if let Err(e) = known.remove(ip) { |
| 176 | log::warn!("기기 기록 삭제 실패: {e}"); |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | #[derive(Clone)] |
| 182 | struct Emitter { |
| 183 | tx: mpsc::Sender<ConnEvent>, |
| 184 | waker: Waker, |
| 185 | } |
| 186 | |
| 187 | impl Emitter { |
| 188 | fn emit(&self, event: ConnEvent) { |
| 189 | if self.tx.send(event).is_ok() { |
| 190 | (self.waker)(); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// 세션 시작 때 기기에 요청할 설정. |
| 196 | struct SessionOptions { |
| 197 | video: VideoConfigRequest, |
| 198 | /// 거짓이면 영상 설정을 받은 직후 휴대폰 실제 화면을 끄게 한다. |
| 199 | keep_screen_on: bool, |
| 200 | } |
| 201 | |
| 202 | async fn run( |
| 203 | target: SocketAddr, |
| 204 | identity: Arc<HostIdentity>, |
| 205 | known: Arc<Mutex<KnownDevices>>, |
| 206 | options: SessionOptions, |
| 207 | emit: Emitter, |
| 208 | mut commands: tmpsc::UnboundedReceiver<ConnCommand>, |
| 209 | frames: Arc<FrameSlot>, |
| 210 | ) { |
| 211 | // USB ADB 모드: adb로 데몬을 띄우고 포워딩한 로컬 주소로 접속한다 (기획서 5.4). |
| 212 | let target = if is_usb(target) { |
| 213 | match tokio::task::spawn_blocking(prepare_usb).await { |
| 214 | Ok(Ok(addr)) => addr, |
| 215 | Ok(Err(e)) => { |
| 216 | // 케이블을 잠깐 뽑은 경우처럼 기기가 안 보이는 것만 다시 시도한다. |
| 217 | let retry = matches!(e, AdbError::NoDevice | AdbError::Unauthorized); |
| 218 | emit.emit(ConnEvent::Ended { |
| 219 | reason: e.to_string(), |
| 220 | retry, |
| 221 | }); |
| 222 | return; |
| 223 | } |
| 224 | Err(e) => { |
| 225 | emit.emit(ConnEvent::Ended { |
| 226 | reason: format!("USB 준비 실패: {e}"), |
| 227 | retry: false, |
| 228 | }); |
| 229 | return; |
| 230 | } |
| 231 | } |
| 232 | } else { |
| 233 | target |
| 234 | }; |
| 235 | let pinned = known |
| 236 | .lock() |
| 237 | .unwrap_or_else(|e| e.into_inner()) |
| 238 | .get(target.ip()); |
| 239 | |
| 240 | let on_event = |e: ConnectEvent| match e { |
| 241 | ConnectEvent::TlsEstablished { confirm_code, .. } => { |
| 242 | emit.emit(ConnEvent::Tls { confirm_code }); |
| 243 | } |
| 244 | ConnectEvent::AwaitingApproval { confirm_code } => { |
| 245 | emit.emit(ConnEvent::AwaitingApproval { confirm_code }); |
| 246 | } |
| 247 | }; |
| 248 | let mut session = match connect( |
| 249 | target, |
| 250 | &identity, |
| 251 | pinned, |
| 252 | ConnectOptions::default(), |
| 253 | on_event, |
| 254 | ) |
| 255 | .await |
| 256 | { |
| 257 | Ok(s) => s, |
| 258 | Err(e) => { |
| 259 | emit.emit(ConnEvent::Ended { |
| 260 | reason: describe_connect_error(&e), |
| 261 | retry: connect_error_is_transient(&e), |
| 262 | }); |
| 263 | return; |
| 264 | } |
| 265 | }; |
| 266 | |
| 267 | if session.grant == AuthGrant::Always { |
| 268 | let mut known = known.lock().unwrap_or_else(|e| e.into_inner()); |
| 269 | if let Err(e) = known.insert(target.ip(), session.fingerprint) { |
| 270 | log::warn!("기기 지문 저장 실패: {e}"); |
| 271 | } |
| 272 | } |
| 273 | emit.emit(ConnEvent::Connected { |
| 274 | grant: session.grant, |
| 275 | }); |
| 276 | |
| 277 | // 영상 설정을 먼저 받아 코덱을 알아낸 뒤 영상 채널을 연다 (기획서 7.6 3~4단계). |
| 278 | let config = match request_video_config(session.control(), options.video).await { |
| 279 | Ok(cfg) => cfg, |
| 280 | Err((reason, retry)) => { |
| 281 | emit.emit(ConnEvent::Ended { reason, retry }); |
| 282 | return; |
| 283 | } |
| 284 | }; |
| 285 | emit.emit(ConnEvent::VideoConfig(config)); |
| 286 | |
| 287 | // 세션이 시작됐으니 휴대폰 화면 설정을 적용한다. 연결이 끝나면 휴대폰이 스스로 되돌린다. |
| 288 | // 그 사이 설정 창에서 바꾼 값은 명령 대기열에 있다가 이 뒤에 나가 최종 상태가 된다. |
| 289 | let screen = if options.keep_screen_on { |
| 290 | SystemAction::ScreenOn |
| 291 | } else { |
| 292 | SystemAction::ScreenOff |
| 293 | }; |
| 294 | if let Err(e) = session.control().send(&Message::SystemAction(screen)).await { |
| 295 | emit.emit(ConnEvent::Ended { |
| 296 | reason: format!("연결이 끊겼습니다: {e}"), |
| 297 | retry: true, |
| 298 | }); |
| 299 | return; |
| 300 | } |
| 301 | |
| 302 | let (dec_tx, dec_rx) = mpsc::channel::<DecoderInput>(); |
| 303 | let (keyframe_tx, mut keyframe_rx) = tmpsc::unbounded_channel::<()>(); |
| 304 | let _ = dec_tx.send(DecoderInput::Codec(config.codec)); |
| 305 | let decoder_thread = { |
| 306 | let emit = emit.clone(); |
| 307 | std::thread::Builder::new() |
| 308 | .name("video-decode".to_owned()) |
| 309 | .spawn(move || decode_loop(dec_rx, frames, emit, keyframe_tx)) |
| 310 | }; |
| 311 | if let Err(e) = decoder_thread { |
| 312 | log::error!("디코더 스레드를 만들지 못했습니다: {e}"); |
| 313 | } |
| 314 | |
| 315 | // 영상 채널이 읽기 오류로 끊기면 제어 루프에 알려 세션을 끝낸다 (다시 연결 대상). |
| 316 | let (video_lost_tx, mut video_lost_rx) = tmpsc::unbounded_channel::<String>(); |
| 317 | let video_task = match session.open_video(Duration::from_secs(5)).await { |
| 318 | Ok(mut stream) => { |
| 319 | let dec_tx = dec_tx.clone(); |
| 320 | Some(tokio::spawn(async move { |
| 321 | loop { |
| 322 | match stream.read_packet().await { |
| 323 | Ok((header, data)) => { |
| 324 | if dec_tx.send(DecoderInput::Packet(header, data)).is_err() { |
| 325 | break; |
| 326 | } |
| 327 | } |
| 328 | Err(FramedError::Closed) => { |
| 329 | let _ = video_lost_tx.send("기기가 영상 연결을 닫았습니다".to_owned()); |
| 330 | break; |
| 331 | } |
| 332 | Err(e) => { |
| 333 | let _ = video_lost_tx.send(format!("영상 연결이 끊겼습니다: {e}")); |
| 334 | break; |
| 335 | } |
| 336 | } |
| 337 | } |
| 338 | })) |
| 339 | } |
| 340 | Err(e) => { |
| 341 | log::warn!("영상 채널 연결 실패: {e}"); |
| 342 | None |
| 343 | } |
| 344 | }; |
| 345 | |
| 346 | let (reason, retry) = control_loop( |
| 347 | session.control(), |
| 348 | &mut commands, |
| 349 | &mut keyframe_rx, |
| 350 | &mut video_lost_rx, |
| 351 | &dec_tx, |
| 352 | &emit, |
| 353 | ) |
| 354 | .await; |
| 355 | if let Some(t) = video_task { |
| 356 | t.abort(); |
| 357 | } |
| 358 | // dec_tx가 사라지면 디코더 스레드도 끝난다. |
| 359 | drop(dec_tx); |
| 360 | emit.emit(ConnEvent::Ended { reason, retry }); |
| 361 | } |
| 362 | |
| 363 | /// VIDEO_CONFIG_REQUEST를 보내고 VIDEO_CONFIG 응답을 기다린다. |
| 364 | /// 실패하면 (사유, 다시 연결해 볼 만한지). |
| 365 | async fn request_video_config( |
| 366 | control: &mut wayland_android_remote::net::FramedStream< |
| 367 | wayland_android_remote::net::DeviceStream, |
| 368 | >, |
| 369 | request: VideoConfigRequest, |
| 370 | ) -> Result<VideoConfig, (String, bool)> { |
| 371 | let lost = |e: FramedError| (format!("연결이 끊겼습니다: {e}"), true); |
| 372 | control |
| 373 | .send(&Message::VideoConfigRequest(request)) |
| 374 | .await |
| 375 | .map_err(lost)?; |
| 376 | let wait = async { |
| 377 | loop { |
| 378 | match control.read_message().await { |
| 379 | Ok((_, Message::VideoConfig(cfg))) => return Ok(cfg), |
| 380 | Ok((seq, Message::Ping)) => { |
| 381 | control |
| 382 | .send_with_seq(&Message::Pong, seq) |
| 383 | .await |
| 384 | .map_err(lost)?; |
| 385 | } |
| 386 | Ok((_, Message::Error(e))) => { |
| 387 | return Err(( |
| 388 | format!("기기가 영상을 시작하지 못했습니다: {}", e.reason), |
| 389 | false, |
| 390 | )); |
| 391 | } |
| 392 | Ok(_) => {} |
| 393 | Err(e) => return Err(lost(e)), |
| 394 | } |
| 395 | } |
| 396 | }; |
| 397 | tokio::time::timeout(Duration::from_secs(5), wait) |
| 398 | .await |
| 399 | .map_err(|_| ("영상 설정 응답이 없습니다".to_owned(), true))? |
| 400 | } |
| 401 | |
| 402 | enum DecoderInput { |
| 403 | Codec(VideoCodec), |
| 404 | Packet(VideoPacketHeader, bytes::Bytes), |
| 405 | } |
| 406 | |
| 407 | /// 디코더 스레드. 패킷마다 2~6ms 막히므로 tokio 작업자와 분리한다. |
| 408 | fn decode_loop( |
| 409 | input: mpsc::Receiver<DecoderInput>, |
| 410 | frames: Arc<FrameSlot>, |
| 411 | emit: Emitter, |
| 412 | keyframe: tmpsc::UnboundedSender<()>, |
| 413 | ) { |
| 414 | let mut decoder: Option<Decoder> = None; |
| 415 | let mut count = 0u64; |
| 416 | let mut last_keyframe_request: Option<std::time::Instant> = None; |
| 417 | // 2초마다 디코딩 fps와 평균 디코딩 시간을 남긴다. |
| 418 | let mut stats_since = std::time::Instant::now(); |
| 419 | let (mut stats_frames, mut stats_decode) = (0u32, Duration::ZERO); |
| 420 | while let Ok(msg) = input.recv() { |
| 421 | match msg { |
| 422 | DecoderInput::Codec(codec) => { |
| 423 | if decoder.as_ref().is_some_and(|d| d.codec() == codec) { |
| 424 | continue; |
| 425 | } |
| 426 | match Decoder::new(codec, true) { |
| 427 | Ok(d) => { |
| 428 | log::info!("영상 디코더: {codec:?} {}", d.backend()); |
| 429 | decoder = Some(d); |
| 430 | } |
| 431 | Err(e) => log::error!("디코더 생성 실패: {e}"), |
| 432 | } |
| 433 | } |
| 434 | DecoderInput::Packet(header, data) => { |
| 435 | let Some(d) = decoder.as_mut() else { continue }; |
| 436 | let started = std::time::Instant::now(); |
| 437 | let result = d.decode(&header, &data); |
| 438 | if !header.is_config { |
| 439 | stats_frames += 1; |
| 440 | stats_decode += started.elapsed(); |
| 441 | } |
| 442 | if stats_since.elapsed() >= Duration::from_secs(2) && stats_frames > 0 { |
| 443 | let secs = stats_since.elapsed().as_secs_f64(); |
| 444 | log::info!( |
| 445 | "영상 {:.1}fps, 평균 디코딩 {:.2}ms ({})", |
| 446 | f64::from(stats_frames) / secs, |
| 447 | stats_decode.as_secs_f64() * 1000.0 / f64::from(stats_frames), |
| 448 | d.backend() |
| 449 | ); |
| 450 | stats_since = std::time::Instant::now(); |
| 451 | (stats_frames, stats_decode) = (0, Duration::ZERO); |
| 452 | } |
| 453 | match result { |
| 454 | Ok(out) => { |
| 455 | // 한 번에 여러 프레임이 나오면 최신 것만 그린다. |
| 456 | if let Some(frame) = out.into_iter().last() { |
| 457 | count += 1; |
| 458 | frames.put(Arc::new(to_yuv(frame))); |
| 459 | emit.emit(ConnEvent::VideoFrames(count)); |
| 460 | } |
| 461 | } |
| 462 | Err(e) => { |
| 463 | log::debug!("디코딩 오류: {e}"); |
| 464 | let recent = last_keyframe_request |
| 465 | .is_some_and(|t| t.elapsed() < Duration::from_millis(500)); |
| 466 | if e.needs_keyframe() && !recent { |
| 467 | last_keyframe_request = Some(std::time::Instant::now()); |
| 468 | let _ = keyframe.send(()); |
| 469 | } |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | fn to_yuv(frame: DecodedFrame) -> YuvFrame { |
| 478 | YuvFrame { |
| 479 | width: frame.width, |
| 480 | height: frame.height, |
| 481 | nv12: matches!(frame.layout, PlaneLayout::Nv12), |
| 482 | planes: frame |
| 483 | .planes |
| 484 | .into_iter() |
| 485 | .map(|p| (p.data, p.stride, p.width, p.height)) |
| 486 | .collect(), |
| 487 | bt709: matches!(frame.color.matrix, ColorMatrix::Bt709), |
| 488 | full_range: frame.color.full_range, |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | /// PING 간격. |
| 493 | const PING_INTERVAL: Duration = Duration::from_secs(2); |
| 494 | /// 이만큼 PONG이 없으면 연결이 끊긴 것으로 본다 (Wi-Fi 끊김은 TCP 오류가 늦게 온다). |
| 495 | const PONG_TIMEOUT: Duration = Duration::from_secs(6); |
| 496 | |
| 497 | /// 세션이 끝날 때까지 제어 채널을 처리한다. 끝나면 (사유, 다시 연결해 볼 만한지). |
| 498 | async fn control_loop( |
| 499 | control: &mut wayland_android_remote::net::FramedStream< |
| 500 | wayland_android_remote::net::DeviceStream, |
| 501 | >, |
| 502 | commands: &mut tmpsc::UnboundedReceiver<ConnCommand>, |
| 503 | keyframe: &mut tmpsc::UnboundedReceiver<()>, |
| 504 | video_lost: &mut tmpsc::UnboundedReceiver<String>, |
| 505 | decoder: &mpsc::Sender<DecoderInput>, |
| 506 | emit: &Emitter, |
| 507 | ) -> (String, bool) { |
| 508 | let lost = |e: FramedError| (format!("연결이 끊겼습니다: {e}"), true); |
| 509 | let mut ping = tokio::time::interval(PING_INTERVAL); |
| 510 | let mut last_pong = tokio::time::Instant::now(); |
| 511 | let mut outbox = transfer::Outbox::default(); |
| 512 | loop { |
| 513 | tokio::select! { |
| 514 | // 위에 있는 갈래가 먼저다. 파일 데이터는 맨 아래에 두어 입력과 PING을 앞세운다. |
| 515 | biased; |
| 516 | msg = control.read_message() => match msg { |
| 517 | Ok((seq, Message::Ping)) => { |
| 518 | if let Err(e) = control.send_with_seq(&Message::Pong, seq).await { |
| 519 | return lost(e); |
| 520 | } |
| 521 | } |
| 522 | Ok((_, Message::Pong)) => last_pong = tokio::time::Instant::now(), |
| 523 | Ok((_, Message::VideoConfig(cfg))) => { |
| 524 | let _ = decoder.send(DecoderInput::Codec(cfg.codec)); |
| 525 | emit.emit(ConnEvent::VideoConfig(cfg)); |
| 526 | } |
| 527 | Ok((_, Message::ClipboardSync(c))) => { |
| 528 | if c.origin == ClipboardOrigin::AndroidDevice { |
| 529 | log::info!("휴대폰 클립보드 수신: {:?} {} 바이트", c.mime(), c.content.bytes().len()); |
| 530 | emit.emit(ConnEvent::Clipboard(c.content, c.sha256)); |
| 531 | } else { |
| 532 | log::debug!("기기가 호스트 출처 클립보드를 보냈습니다. 무시합니다"); |
| 533 | } |
| 534 | } |
| 535 | Ok((_, Message::Error(e))) if e.code == error_code::PERMISSION_DENIED => { |
| 536 | // 휴대폰에서 이 PC의 허용을 철회했다. 다시 접속하면 승인 창이 뜨므로 재연결하지 않는다. |
| 537 | let reason = if e.reason.is_empty() { "휴대폰에서 이 PC의 허용을 철회했습니다".to_owned() } else { e.reason }; |
| 538 | return (reason, false); |
| 539 | } |
| 540 | Ok((_, Message::FileResult(r))) => { |
| 541 | if let Some(n) = outbox.on_result(&r) { |
| 542 | emit.emit(ConnEvent::Transfer(n)); |
| 543 | } |
| 544 | } |
| 545 | Ok((_, Message::Error(e))) => log::warn!("기기 오류: {:#06x} {}", e.code, e.reason), |
| 546 | Ok((_, other)) => log::debug!("처리하지 않은 메시지: {:?}", other.msg_type()), |
| 547 | Err(FramedError::Closed) => return ("기기가 연결을 닫았습니다".to_owned(), true), |
| 548 | Err(e) => return lost(e), |
| 549 | }, |
| 550 | cmd = commands.recv() => { |
| 551 | let msg = match cmd { |
| 552 | Some(ConnCommand::System(a)) => Message::SystemAction(a), |
| 553 | Some(ConnCommand::RequestVideo(r)) => Message::VideoConfigRequest(r), |
| 554 | Some(ConnCommand::Input(m)) => m, |
| 555 | Some(ConnCommand::SendFiles(paths)) => { |
| 556 | let (items, skipped) = transfer::collect(&paths); |
| 557 | log::info!("파일 전송 요청: {}개 (건너뜀 {skipped})", items.len()); |
| 558 | outbox.enqueue(items); |
| 559 | outbox.add_skipped(skipped); |
| 560 | if let Some(n) = outbox.finish_if_idle() { |
| 561 | emit.emit(ConnEvent::Transfer(n)); |
| 562 | } |
| 563 | continue; |
| 564 | } |
| 565 | None => return ("연결을 끊었습니다".to_owned(), false), |
| 566 | }; |
| 567 | if let Err(e) = control.send(&msg).await { |
| 568 | return lost(e); |
| 569 | } |
| 570 | } |
| 571 | Some(()) = keyframe.recv() => { |
| 572 | if let Err(e) = control.send(&Message::VideoRequestKeyframe).await { |
| 573 | return lost(e); |
| 574 | } |
| 575 | } |
| 576 | Some(reason) = video_lost.recv() => return (reason, true), |
| 577 | _ = ping.tick() => { |
| 578 | if let Err(e) = control.send(&Message::Ping).await { |
| 579 | return lost(e); |
| 580 | } |
| 581 | } |
| 582 | _ = tokio::time::sleep_until(last_pong + PONG_TIMEOUT) => { |
| 583 | return ( |
| 584 | format!("기기 응답이 없습니다 ({}초)", PONG_TIMEOUT.as_secs()), |
| 585 | true, |
| 586 | ); |
| 587 | } |
| 588 | _ = std::future::ready(()), if outbox.has_work() => { |
| 589 | if let Some(msg) = outbox.next_message() |
| 590 | && let Err(e) = control.send(&msg).await |
| 591 | { |
| 592 | return lost(e); |
| 593 | } |
| 594 | if let Some(n) = outbox.progress(std::time::Instant::now()) { |
| 595 | emit.emit(ConnEvent::Transfer(n)); |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | /// 접속 단계 오류 중 네트워크 문제(다시 시도하면 될 수 있는 것)인지. |
| 603 | /// 지문 불일치·거부·인증 실패·프로토콜 오류는 다시 시도해도 같으므로 거짓. |
| 604 | fn connect_error_is_transient(e: &ConnectError) -> bool { |
| 605 | match e { |
| 606 | ConnectError::Io(_) | ConnectError::Tls(_) | ConnectError::Timeout(_) => true, |
| 607 | ConnectError::Protocol(f) => matches!(f, FramedError::Io(_) | FramedError::Closed), |
| 608 | ConnectError::FingerprintMismatch { .. } |
| 609 | | ConnectError::ChallengeRejected |
| 610 | | ConnectError::AuthFailed(_) |
| 611 | | ConnectError::Unexpected(_) => false, |
| 612 | } |
| 613 | } |
| 614 | |
| 615 | fn describe_connect_error(e: &ConnectError) -> String { |
| 616 | match e { |
| 617 | ConnectError::Io(io) if io.kind() == std::io::ErrorKind::ConnectionRefused => { |
| 618 | "휴대폰에서 Android Remote 앱을 열어 서비스를 켜 주세요".to_owned() |
| 619 | } |
| 620 | ConnectError::Timeout("연결") => "기기에 연결할 수 없습니다 (시간 초과)".to_owned(), |
| 621 | other => other.to_string(), |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | /// 사이드 메뉴 설정을 영상 설정 요청으로 바꾼다. |
| 626 | pub fn video_request(max_size: u16, max_fps: u8, bitrate_mbps: u32) -> VideoConfigRequest { |
| 627 | VideoConfigRequest { |
| 628 | max_size, |
| 629 | max_fps, |
| 630 | // 호스트는 NVDEC/VA-API로 세 코덱 모두 하드웨어 디코딩할 수 있다고 가정한다. |
| 631 | // 디코더를 붙일 때 실제 지원 여부로 바꾼다. |
| 632 | codecs: CodecMask::H264 | CodecMask::H265 | CodecMask::AV1, |
| 633 | bitrate: bitrate_mbps * 1_000_000, |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[cfg(test)] |
| 638 | mod tests { |
| 639 | use super::*; |
| 640 | use wayland_android_remote::protocol::AuthResultCode; |
| 641 | |
| 642 | #[test] |
| 643 | fn only_network_errors_are_retried() { |
| 644 | let io = || std::io::Error::new(std::io::ErrorKind::ConnectionReset, "reset"); |
| 645 | assert!(connect_error_is_transient(&ConnectError::Io(io()))); |
| 646 | assert!(connect_error_is_transient(&ConnectError::Timeout("연결"))); |
| 647 | assert!(connect_error_is_transient(&ConnectError::Protocol( |
| 648 | FramedError::Closed |
| 649 | ))); |
| 650 | assert!(!connect_error_is_transient( |
| 651 | &ConnectError::FingerprintMismatch { |
| 652 | expected: [0; 32], |
| 653 | actual: [1; 32], |
| 654 | } |
| 655 | )); |
| 656 | assert!(!connect_error_is_transient( |
| 657 | &ConnectError::ChallengeRejected |
| 658 | )); |
| 659 | for code in [AuthResultCode::Rejected, AuthResultCode::Revoked] { |
| 660 | assert!(!connect_error_is_transient(&ConnectError::AuthFailed(code))); |
| 661 | } |
| 662 | } |
| 663 | } |