leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

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