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