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