leejunyoung5819wayland-android-remote

공개

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

758줄26 KB
1//! 가짜 기기 서버: Android 쉘 데몬과 같은 프로토콜을 말하는 테스트용 서버.
2//!
3//! 연결마다 TLS 1.3 수락 후 첫 프레임으로 역할을 정한다.
4//! AUTH_HELLO → 제어 채널, CHANNEL_ATTACH → 비디오 채널.
5//! 통합 테스트(`mod common;`)와 `examples/fake_device.rs`가 함께 쓴다.
6#![allow(dead_code)]
7
8use std::io;
9use std::net::SocketAddr;
10use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
11use std::sync::{Arc, Mutex};
12use std::time::Duration;
13
14use bytes::BytesMut;
15use ed25519_dalek::{Signature, VerifyingKey};
16use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
17use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
18use tokio::net::{TcpListener, TcpStream};
19use tokio::sync::{Notify, watch};
20use tokio::task::{JoinHandle, JoinSet};
21use tokio_rustls::TlsAcceptor;
22use wayland_android_remote::net::{FramedError, FramedStream};
23use wayland_android_remote::protocol::{
24 AuthChallenge, AuthGrant, AuthHello, AuthResponse, AuthResult, AuthResultCode, AuthStatus,
25 ChannelAttach, ChannelKind, CodecMask, ErrorMessage, Message, ProtocolError, VideoCodec,
26 VideoConfig, VideoConfigRequest, VideoPacketHeader, auth_signing_message, cert_fingerprint,
27 confirm_code, error_code, fingerprint_hex,
28};
29
30/// 기기 화면 해상도 (세로 기준).
31pub const DISPLAY_WIDTH: u16 = 1080;
32pub const DISPLAY_HEIGHT: u16 = 2400;
33/// 비디오 프레임 간격 (60fps).
34pub const FRAME_INTERVAL_US: u64 = 16_666;
35
36/// 가짜 비트스트림. 실제 디코딩은 되지 않는다.
37const DUMMY_CONFIG: &[u8] = b"\x00\x00\x00\x01gSPS-fake\x00\x00\x00\x01hPPS-fake";
38const DUMMY_KEYFRAME: &[u8] = b"\x00\x00\x00\x01eIDR-fake";
39const DUMMY_FRAME: &[u8] = b"\x00\x00\x00\x01aP-fake";
40
41/// 화이트리스트에 없는 키가 왔을 때 폰 사용자의 반응.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum PendingPolicy {
44 /// `after` 뒤 "항상 허용": OK/ALWAYS, 화이트리스트에 추가.
45 ApproveAlways { after: Duration },
46 /// `after` 뒤 "이번만 허용": OK/ONCE.
47 ApproveOnce { after: Duration },
48 /// `after` 뒤 거부: REJECTED/NONE.
49 Reject { after: Duration },
50 /// 응답하지 않음. 클라이언트가 끊을 때까지 연결 유지.
51 NeverAnswer,
52}
53
54#[derive(Debug, Clone)]
55pub struct FakeDeviceConfig {
56 pub pending: PendingPolicy,
57 pub whitelist: Vec<[u8; 32]>,
58 pub daemon_version: u32,
59 /// 기기 인코더가 지원하는 코덱.
60 pub encoders: CodecMask,
61 /// KEYFRAME 뒤에 보낼 일반 프레임 수.
62 pub video_frames: usize,
63}
64
65impl Default for FakeDeviceConfig {
66 fn default() -> Self {
67 Self {
68 pending: PendingPolicy::ApproveAlways {
69 after: Duration::from_millis(50),
70 },
71 whitelist: Vec::new(),
72 daemon_version: 1,
73 encoders: CodecMask::H264 | CodecMask::H265,
74 video_frames: 30,
75 }
76 }
77}
78
79/// 실행 중인 가짜 기기. drop 또는 [`FakeDevice::shutdown`] 시 모든 연결을 끊는다.
80pub struct FakeDevice {
81 addr: SocketAddr,
82 shared: Arc<Shared>,
83 task: JoinHandle<()>,
84}
85
86impl FakeDevice {
87 /// 새 자체 서명 인증서를 만들고 `bind`에서 수신을 시작한다.
88 pub async fn start(bind: SocketAddr, config: FakeDeviceConfig) -> io::Result<FakeDevice> {
89 let ck = rcgen::generate_simple_self_signed(vec!["android-remote-device".to_owned()])
90 .map_err(io::Error::other)?;
91 let cert_der: CertificateDer<'static> = ck.cert.der().clone();
92 let cert_sha256 = cert_fingerprint(&cert_der);
93 let key_der =
94 PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(ck.signing_key.serialize_der()));
95
96 // TLS 1.3 전용, 클라이언트 인증 없음. 세션 저장소는 기본값(재개 지원), 0-RTT 없음.
97 let provider = Arc::new(rustls::crypto::ring::default_provider());
98 let tls = rustls::ServerConfig::builder_with_provider(provider)
99 .with_protocol_versions(&[&rustls::version::TLS13])
100 .map_err(io::Error::other)?
101 .with_no_client_auth()
102 .with_single_cert(vec![cert_der], key_der)
103 .map_err(io::Error::other)?;
104 let acceptor = TlsAcceptor::from(Arc::new(tls));
105
106 let listener = TcpListener::bind(bind).await?;
107 let addr = listener.local_addr()?;
108 let shared = Arc::new(Shared {
109 whitelist: Mutex::new(config.whitelist.clone()),
110 config,
111 cert_sha256,
112 prompts: AtomicUsize::new(0),
113 sessions: Mutex::new(Vec::new()),
114 next_session_id: AtomicU64::new(0),
115 });
116 let task = tokio::spawn(accept_loop(listener, acceptor, shared.clone()));
117 log::info!(
118 "가짜 기기 시작: {addr}, 인증서 SHA-256 {}",
119 fingerprint_hex(&cert_sha256)
120 );
121 Ok(FakeDevice { addr, shared, task })
122 }
123
124 pub fn addr(&self) -> SocketAddr {
125 self.addr
126 }
127
128 pub fn cert_sha256(&self) -> [u8; 32] {
129 self.shared.cert_sha256
130 }
131
132 /// 승인 팝업에 표시되는 6자리 확인 코드.
133 pub fn confirm_code(&self) -> String {
134 confirm_code(&self.shared.cert_sha256)
135 }
136
137 pub fn whitelist(&self) -> Vec<[u8; 32]> {
138 self.shared.whitelist.lock().unwrap().clone()
139 }
140
141 /// 지금까지 표시한 승인 팝업 수 (PENDING_USER 후 서명이 유효했던 경우).
142 pub fn approval_prompts(&self) -> usize {
143 self.shared.prompts.load(Ordering::SeqCst)
144 }
145
146 /// 수신 루프와 모든 연결을 중단한다.
147 pub fn shutdown(self) {
148 self.task.abort();
149 }
150}
151
152impl Drop for FakeDevice {
153 fn drop(&mut self) {
154 self.task.abort();
155 }
156}
157
158// ---------------------------------------------------------------------------
159// 공유 상태
160// ---------------------------------------------------------------------------
161
162struct Shared {
163 config: FakeDeviceConfig,
164 cert_sha256: [u8; 32],
165 whitelist: Mutex<Vec<[u8; 32]>>,
166 prompts: AtomicUsize,
167 sessions: Mutex<Vec<SessionEntry>>,
168 next_session_id: AtomicU64,
169}
170
171/// 제어 연결이 살아 있는 동안 유효한 세션 토큰.
172struct SessionEntry {
173 id: u64,
174 token: [u8; 32],
175 used: bool,
176 state: Arc<SessionState>,
177 /// 제어 연결이 끝나면 sender가 drop되어 `changed()`가 Err를 낸다.
178 alive: watch::Receiver<()>,
179}
180
181/// 제어 채널 → 비디오 채널 신호.
182struct SessionState {
183 config_gen: watch::Sender<u8>,
184 keyframe_requested: AtomicBool,
185 keyframe_notify: Notify,
186}
187
188impl SessionState {
189 fn request_keyframe(&self) {
190 self.keyframe_requested.store(true, Ordering::SeqCst);
191 self.keyframe_notify.notify_one();
192 }
193
194 fn take_keyframe_request(&self) -> bool {
195 self.keyframe_requested.swap(false, Ordering::SeqCst)
196 }
197}
198
199impl Shared {
200 /// 토큰이 등록되어 있고 아직 안 쓰였으면 사용 처리하고 세션을 돌려준다.
201 fn claim_token(&self, token: &[u8; 32]) -> Option<(Arc<SessionState>, watch::Receiver<()>)> {
202 let mut sessions = self.sessions.lock().unwrap();
203 // 조기 종료 없이 전체를 상수 시간 비교한다.
204 let mut found = None;
205 for (i, s) in sessions.iter().enumerate() {
206 if ct_eq(&s.token, token) {
207 found = Some(i);
208 }
209 }
210 let entry = &mut sessions[found?];
211 if entry.used {
212 return None;
213 }
214 entry.used = true;
215 Some((entry.state.clone(), entry.alive.clone()))
216 }
217}
218
219/// 제어 연결 종료(중단 포함) 시 토큰을 지운다.
220struct SessionGuard {
221 shared: Arc<Shared>,
222 id: u64,
223}
224
225impl Drop for SessionGuard {
226 fn drop(&mut self) {
227 self.shared
228 .sessions
229 .lock()
230 .unwrap()
231 .retain(|s| s.id != self.id);
232 }
233}
234
235fn ct_eq(a: &[u8; 32], b: &[u8; 32]) -> bool {
236 a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
237}
238
239fn short_hex(bytes: &[u8]) -> String {
240 bytes[..4].iter().map(|b| format!("{b:02x}")).collect()
241}
242
243fn random32() -> [u8; 32] {
244 let mut out = [0u8; 32];
245 getrandom::fill(&mut out).expect("OS 난수 생성 실패");
246 out
247}
248
249// ---------------------------------------------------------------------------
250// 연결 수락
251// ---------------------------------------------------------------------------
252
253async fn accept_loop(listener: TcpListener, acceptor: TlsAcceptor, shared: Arc<Shared>) {
254 // 이 태스크가 중단되면 JoinSet drop으로 모든 연결 태스크도 중단된다.
255 let mut conns = JoinSet::new();
256 loop {
257 tokio::select! {
258 res = listener.accept() => match res {
259 Ok((tcp, peer)) => {
260 conns.spawn(handle_conn(tcp, peer, acceptor.clone(), shared.clone()));
261 }
262 Err(e) => {
263 log::warn!("accept 실패: {e}");
264 tokio::time::sleep(Duration::from_millis(10)).await;
265 }
266 },
267 Some(_) = conns.join_next(), if !conns.is_empty() => {}
268 }
269 }
270}
271
272async fn handle_conn(tcp: TcpStream, peer: SocketAddr, acceptor: TlsAcceptor, shared: Arc<Shared>) {
273 let _ = tcp.set_nodelay(true);
274 let tls = match acceptor.accept(tcp).await {
275 Ok(s) => s,
276 Err(e) => {
277 log::warn!("[{peer}] TLS 핸드셰이크 실패: {e}");
278 return;
279 }
280 };
281 let mut framed = FramedStream::new(tls);
282 match framed.read_message().await {
283 Ok((_, Message::AuthHello(hello))) => run_control(framed, hello, peer, shared).await,
284 Ok((_, Message::ChannelAttach(attach))) => {
285 run_video(framed.into_inner(), attach, peer, shared).await
286 }
287 Ok((_, other)) => {
288 log::warn!(
289 "[{peer}] 첫 프레임이 {:?}: UNAUTHENTICATED",
290 other.msg_type()
291 );
292 close_with_error(framed, error_code::UNAUTHENTICATED, "인증 필요").await;
293 }
294 Err(e) => log::warn!("[{peer}] 첫 프레임 읽기 실패: {e}"),
295 }
296}
297
298/// ERROR를 보내고 TLS close_notify 후 닫는다.
299async fn close_with_error<S: AsyncRead + AsyncWrite + Unpin>(
300 mut framed: FramedStream<S>,
301 code: u16,
302 reason: &str,
303) {
304 let msg = Message::Error(ErrorMessage {
305 code,
306 reason: reason.to_owned(),
307 });
308 let _ = framed.send(&msg).await;
309 let _ = framed.into_inner().shutdown().await;
310}
311
312async fn close<S: AsyncRead + AsyncWrite + Unpin>(framed: FramedStream<S>) {
313 let _ = framed.into_inner().shutdown().await;
314}
315
316// ---------------------------------------------------------------------------
317// 제어 채널
318// ---------------------------------------------------------------------------
319
320/// 인증 전 프레임 처리 결과.
321enum PreAuth {
322 Response(AuthResponse),
323 /// 처리했거나 무시함. 계속 읽는다.
324 Continue,
325 /// 인증 전 금지 메시지: ERROR 후 종료.
326 Unauthenticated,
327 /// 연결 종료 또는 복구 불가 오류.
328 Gone,
329}
330
331/// 인증 전 수신 프레임을 처리한다. PING에는 PONG을 보낸다.
332async fn pre_auth_step<S: AsyncRead + AsyncWrite + Unpin>(
333 framed: &mut FramedStream<S>,
334 res: Result<(u16, Message), FramedError>,
335 peer: SocketAddr,
336) -> PreAuth {
337 match res {
338 Ok((seq, Message::Ping)) => match framed.send_with_seq(&Message::Pong, seq).await {
339 Ok(()) => PreAuth::Continue,
340 Err(_) => PreAuth::Gone,
341 },
342 Ok((_, Message::AuthResponse(r))) => PreAuth::Response(r),
343 Ok((_, m)) if m.msg_type().allowed_before_auth() => {
344 log::info!("[{peer}] 인증 중 {:?} 무시", m.msg_type());
345 PreAuth::Continue
346 }
347 Ok((_, m)) => {
348 log::warn!("[{peer}] 인증 전 {:?}: UNAUTHENTICATED", m.msg_type());
349 PreAuth::Unauthenticated
350 }
351 Err(FramedError::Closed) => {
352 log::info!("[{peer}] 인증 중 클라이언트 종료");
353 PreAuth::Gone
354 }
355 Err(e) => {
356 log::warn!("[{peer}] 인증 중 오류: {e}");
357 PreAuth::Gone
358 }
359 }
360}
361
362/// 사용자 승인 대기. `after`가 None이면 무한 대기. 클라이언트가 떠나면 false.
363async fn wait_approval<S: AsyncRead + AsyncWrite + Unpin>(
364 framed: &mut FramedStream<S>,
365 after: Option<Duration>,
366 peer: SocketAddr,
367) -> bool {
368 let sleep = async {
369 match after {
370 Some(d) => tokio::time::sleep(d).await,
371 None => std::future::pending().await,
372 }
373 };
374 tokio::pin!(sleep);
375 loop {
376 tokio::select! {
377 () = &mut sleep => return true,
378 res = framed.read_message() => match pre_auth_step(framed, res, peer).await {
379 PreAuth::Continue => {}
380 PreAuth::Response(_) => log::info!("[{peer}] 승인 대기 중 AUTH_RESPONSE 재수신 무시"),
381 PreAuth::Unauthenticated => {
382 let msg = Message::Error(ErrorMessage {
383 code: error_code::UNAUTHENTICATED,
384 reason: "인증 필요".to_owned(),
385 });
386 let _ = framed.send(&msg).await;
387 return false;
388 }
389 PreAuth::Gone => return false,
390 },
391 }
392 }
393}
394
395fn auth_result(shared: &Shared, result: AuthResultCode) -> Message {
396 Message::AuthResult(AuthResult {
397 result,
398 grant: AuthGrant::None,
399 session_token: [0; 32],
400 daemon_version: shared.config.daemon_version,
401 })
402}
403
404async fn run_control<S: AsyncRead + AsyncWrite + Unpin>(
405 mut framed: FramedStream<S>,
406 hello: AuthHello,
407 peer: SocketAddr,
408 shared: Arc<Shared>,
409) {
410 let key = hello.public_key;
411 let whitelisted = shared.whitelist.lock().unwrap().contains(&key);
412 let status = if whitelisted {
413 AuthStatus::Approved
414 } else {
415 AuthStatus::PendingUser
416 };
417 let nonce = random32();
418 log::info!(
419 "[{peer}] AUTH_HELLO host={:?} key={}… → AUTH_CHALLENGE {status:?}",
420 hello.hostname,
421 short_hex(&key)
422 );
423 let challenge = Message::AuthChallenge(AuthChallenge { status, nonce });
424 if framed.send(&challenge).await.is_err() {
425 return;
426 }
427
428 // 1. AUTH_RESPONSE 수신
429 let resp = loop {
430 let res = framed.read_message().await;
431 match pre_auth_step(&mut framed, res, peer).await {
432 PreAuth::Response(r) => break r,
433 PreAuth::Continue => {}
434 PreAuth::Unauthenticated => {
435 close_with_error(framed, error_code::UNAUTHENTICATED, "인증 필요").await;
436 return;
437 }
438 PreAuth::Gone => return,
439 }
440 };
441
442 // 2. 서명 검증
443 let signed = auth_signing_message(&nonce, &shared.cert_sha256);
444 let valid = VerifyingKey::from_bytes(&key)
445 .and_then(|vk| vk.verify_strict(&signed, &Signature::from_bytes(&resp.signature)))
446 .is_ok();
447 if !valid {
448 log::warn!("[{peer}] 서명 불일치 → AUTH_RESULT SIGNATURE_INVALID");
449 let _ = framed
450 .send(&auth_result(&shared, AuthResultCode::SignatureInvalid))
451 .await;
452 close(framed).await;
453 return;
454 }
455 log::info!("[{peer}] 서명 확인");
456
457 // 3. 승인 결정
458 let grant = if whitelisted {
459 AuthGrant::Always
460 } else {
461 shared.prompts.fetch_add(1, Ordering::SeqCst);
462 log::info!(
463 "[{peer}] 승인 팝업 표시 (확인 코드 {}), 정책 {:?}",
464 confirm_code(&shared.cert_sha256),
465 shared.config.pending
466 );
467 match shared.config.pending {
468 PendingPolicy::ApproveAlways { after } => {
469 if !wait_approval(&mut framed, Some(after), peer).await {
470 return;
471 }
472 let mut wl = shared.whitelist.lock().unwrap();
473 if !wl.contains(&key) {
474 wl.push(key);
475 }
476 AuthGrant::Always
477 }
478 PendingPolicy::ApproveOnce { after } => {
479 if !wait_approval(&mut framed, Some(after), peer).await {
480 return;
481 }
482 AuthGrant::Once
483 }
484 PendingPolicy::Reject { after } => {
485 if wait_approval(&mut framed, Some(after), peer).await {
486 log::info!("[{peer}] 사용자 거부 → AUTH_RESULT REJECTED");
487 let _ = framed
488 .send(&auth_result(&shared, AuthResultCode::Rejected))
489 .await;
490 close(framed).await;
491 }
492 return;
493 }
494 PendingPolicy::NeverAnswer => {
495 wait_approval(&mut framed, None, peer).await;
496 log::info!("[{peer}] 응답 없이 대기하다 클라이언트 종료");
497 return;
498 }
499 }
500 };
501
502 // 4. 세션 등록
503 let token = random32();
504 let (alive_tx, alive_rx) = watch::channel(());
505 let state = Arc::new(SessionState {
506 config_gen: watch::Sender::new(1),
507 keyframe_requested: AtomicBool::new(false),
508 keyframe_notify: Notify::new(),
509 });
510 let id = shared.next_session_id.fetch_add(1, Ordering::SeqCst);
511 shared.sessions.lock().unwrap().push(SessionEntry {
512 id,
513 token,
514 used: false,
515 state: state.clone(),
516 alive: alive_rx,
517 });
518 let _guard = SessionGuard {
519 shared: shared.clone(),
520 id,
521 };
522 let _alive_tx = alive_tx;
523
524 let ok = Message::AuthResult(AuthResult {
525 result: AuthResultCode::Ok,
526 grant,
527 session_token: token,
528 daemon_version: shared.config.daemon_version,
529 });
530 if framed.send(&ok).await.is_err() {
531 return;
532 }
533 log::info!("[{peer}] AUTH_RESULT OK/{grant:?}, 세션 시작");
534
535 serve_control(framed, &state, peer, &shared).await;
536 log::info!("[{peer}] 제어 연결 종료, 토큰 폐기");
537}
538
539async fn serve_control<S: AsyncRead + AsyncWrite + Unpin>(
540 mut framed: FramedStream<S>,
541 state: &SessionState,
542 peer: SocketAddr,
543 shared: &Shared,
544) {
545 let mut requests: u8 = 0;
546 loop {
547 let res = match framed.read_message().await {
548 Ok((seq, Message::Ping)) => framed.send_with_seq(&Message::Pong, seq).await,
549 Ok((_, Message::VideoConfigRequest(req))) => {
550 match choose_video_config(&req, shared.config.encoders, requests.wrapping_add(1)) {
551 Some(cfg) => {
552 requests = cfg.config_gen;
553 log::info!("[{peer}] {req:?} → {cfg:?}");
554 let r = framed.send(&Message::VideoConfig(cfg)).await.map(|_| ());
555 // VIDEO_CONFIG를 먼저 보낸 뒤 비디오 채널에 세대 변경을 알린다.
556 state.config_gen.send_if_modified(|g| {
557 let changed = *g != cfg.config_gen;
558 *g = cfg.config_gen;
559 changed
560 });
561 r
562 }
563 None => {
564 log::warn!("[{peer}] {req:?}: 공통 코덱 없음");
565 let msg = Message::Error(ErrorMessage {
566 code: error_code::INTERNAL,
567 reason: "지원하는 공통 코덱 없음".to_owned(),
568 });
569 framed.send(&msg).await.map(|_| ())
570 }
571 }
572 }
573 Ok((_, Message::VideoRequestKeyframe)) => {
574 log::info!("[{peer}] 키프레임 요청");
575 state.request_keyframe();
576 Ok(())
577 }
578 Ok((_, m)) => {
579 log::info!("[{peer}] {:?} 무시", m.msg_type());
580 Ok(())
581 }
582 Err(FramedError::Closed) => return,
583 Err(FramedError::Protocol(e @ ProtocolError::InvalidPayload { .. })) => {
584 // 프레임 경계는 유지되므로 알리고 계속한다.
585 log::warn!("[{peer}] {e}");
586 let msg = Message::Error(ErrorMessage {
587 code: error_code::BAD_FRAME,
588 reason: e.to_string(),
589 });
590 framed.send(&msg).await.map(|_| ())
591 }
592 Err(e) => {
593 log::warn!("[{peer}] 제어 연결 오류: {e}");
594 return;
595 }
596 };
597 if res.is_err() {
598 return;
599 }
600 }
601}
602
603/// 코덱(AV1 > H265 > H264)·해상도·fps를 정한다. 공통 코덱이 없으면 None.
604fn choose_video_config(
605 req: &VideoConfigRequest,
606 encoders: CodecMask,
607 config_gen: u8,
608) -> Option<VideoConfig> {
609 let codec = [VideoCodec::Av1, VideoCodec::H265, VideoCodec::H264]
610 .into_iter()
611 .find(|&c| req.codecs.contains_codec(c) && encoders.contains_codec(c))?;
612 let (width, height) = scaled_size(req.max_size);
613 let fps = if req.max_fps == 0 { 60 } else { req.max_fps }.min(120);
614 Some(VideoConfig {
615 codec,
616 // 0은 건너뛴다 (세대 1부터 시작).
617 config_gen: if config_gen == 0 { 1 } else { config_gen },
618 width,
619 height,
620 fps,
621 bitrate: req.bitrate,
622 display_width: DISPLAY_WIDTH,
623 display_height: DISPLAY_HEIGHT,
624 })
625}
626
627/// 긴 변이 `max_size` 이하가 되도록 비율 유지 축소, 짝수로 내림. 0이면 원본.
628fn scaled_size(max_size: u16) -> (u16, u16) {
629 let (w, h) = (u32::from(DISPLAY_WIDTH), u32::from(DISPLAY_HEIGHT));
630 let long = w.max(h);
631 let max = u32::from(max_size);
632 let (w, h) = if max == 0 || max >= long {
633 (w, h)
634 } else {
635 (w * max / long, h * max / long)
636 };
637 ((w & !1) as u16, (h & !1) as u16)
638}
639
640// ---------------------------------------------------------------------------
641// 비디오 채널
642// ---------------------------------------------------------------------------
643
644async fn run_video<S: AsyncRead + AsyncWrite + Unpin>(
645 mut stream: S,
646 attach: ChannelAttach,
647 peer: SocketAddr,
648 shared: Arc<Shared>,
649) {
650 let claimed = if attach.kind == ChannelKind::Video {
651 shared.claim_token(&attach.session_token)
652 } else {
653 None
654 };
655 let Some((state, mut alive)) = claimed else {
656 log::warn!(
657 "[{peer}] CHANNEL_ATTACH {:?} 거부 (토큰 무효·재사용 또는 종류 불일치)",
658 attach.kind
659 );
660 let _ = stream.shutdown().await;
661 return;
662 };
663 log::info!("[{peer}] 비디오 채널 연결");
664
665 let (mut rd, mut wr) = tokio::io::split(stream);
666 let mut gen_rx = state.config_gen.subscribe();
667 let mut config_gen = *gen_rx.borrow_and_update();
668 let mut pts = 0u64;
669
670 let start = async {
671 write_packet(&mut wr, 0, true, false, config_gen, DUMMY_CONFIG).await?;
672 write_packet(&mut wr, 0, false, true, config_gen, DUMMY_KEYFRAME).await
673 };
674 if start.await.is_err() {
675 return;
676 }
677 // 시작 키프레임으로 이미 충족된 요청은 버린다.
678 state.take_keyframe_request();
679
680 let frames = shared.config.video_frames;
681 let mut sent = 0usize;
682 let mut tick = tokio::time::interval(Duration::from_micros(FRAME_INTERVAL_US));
683 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
684 tick.tick().await;
685 let mut buf = [0u8; 512];
686
687 loop {
688 let res = tokio::select! {
689 _ = tick.tick(), if sent < frames => {
690 pts += FRAME_INTERVAL_US;
691 sent += 1;
692 let key = state.take_keyframe_request();
693 let data = if key { DUMMY_KEYFRAME } else { DUMMY_FRAME };
694 write_packet(&mut wr, pts, false, key, config_gen, data).await
695 }
696 // 프레임 전송이 끝난 뒤에도 키프레임 요청에는 응답한다.
697 () = state.keyframe_notify.notified(), if sent >= frames => {
698 if state.take_keyframe_request() {
699 pts += FRAME_INTERVAL_US;
700 write_packet(&mut wr, pts, false, true, config_gen, DUMMY_KEYFRAME).await
701 } else {
702 Ok(())
703 }
704 }
705 // 설정이 바뀌면 인코더 재시작처럼 CONFIG + KEYFRAME을 새 세대로 보낸다.
706 r = gen_rx.changed() => {
707 if r.is_err() {
708 break;
709 }
710 config_gen = *gen_rx.borrow_and_update();
711 state.take_keyframe_request();
712 pts += FRAME_INTERVAL_US;
713 match write_packet(&mut wr, pts, true, false, config_gen, DUMMY_CONFIG).await {
714 Ok(()) => write_packet(&mut wr, pts, false, true, config_gen, DUMMY_KEYFRAME).await,
715 Err(e) => Err(e),
716 }
717 }
718 _ = alive.changed() => {
719 log::info!("[{peer}] 제어 연결 종료로 비디오 채널 닫음");
720 break;
721 }
722 r = rd.read(&mut buf) => match r {
723 Ok(0) | Err(_) => {
724 log::info!("[{peer}] 비디오 채널: 상대가 닫음");
725 return;
726 }
727 Ok(_) => Ok(()),
728 },
729 };
730 if res.is_err() {
731 log::info!("[{peer}] 비디오 채널 쓰기 실패");
732 return;
733 }
734 }
735 let _ = wr.shutdown().await;
736}
737
738async fn write_packet<W: AsyncWrite + Unpin>(
739 wr: &mut W,
740 pts_us: u64,
741 is_config: bool,
742 is_keyframe: bool,
743 config_gen: u8,
744 data: &[u8],
745) -> io::Result<()> {
746 let header = VideoPacketHeader {
747 pts_us,
748 is_config,
749 is_keyframe,
750 config_gen,
751 data_len: data.len() as u32,
752 };
753 let mut buf = BytesMut::with_capacity(16 + data.len());
754 header.encode(&mut buf);
755 buf.extend_from_slice(data);
756 wr.write_all(&buf).await?;
757 wr.flush().await
758}