leejunyoung5819wayland-android-remote

공개

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

2단계: 휴대폰 화면 스트리밍과 GPU 표시

- 기기: 가상 디스플레이 미러링 + MediaCodec 하드웨어 인코더(AV1>H.265>H.264, B-프레임 없음, CBR), 영상 채널 송신과 지연 우선 프레임 드롭, 키프레임 요청 처리
- 호스트: FFmpeg 디코더(NVDEC > VA-API > 소프트웨어 자동 전환, 저지연 설정), 디코더 스레드와 최신 프레임 슬롯
- 호스트: YUV(NV12/I420) 텍스처를 셰이더에서 RGB로 바꿔 휴대폰 화면 영역에 그리는 wgpu 렌더러
- 시작 인자로 주소를 주면 바로 연결, 2초마다 fps·디코딩 시간 로그
- probe에 영상 녹화 옵션, 영상 렌더러 스냅샷 테스트, 디코더 테스트
- 실제 Galaxy S21+에서 H.265 864x1920 약 60fps, NVDEC 프레임당 약 2.9ms 확인
작성자
LeeJunyoung
작성 시각
커밋
b424ee6a8841fe9846c97d1eb4fecd9bacc67446
부모
06a39d9
이 시점의 파일 보기

변경된 파일 16개

+1,985-53

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정Cargo.lock+86-0
@@ -267,6 +267,23 @@ version = "0.23.1"
267267source = "registry+https://github.com/rust-lang/crates.io-index"
268268checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
269269
270추가: [[package]]
271추가: name = "bindgen"
272추가: version = "0.73.2"
273추가: source = "registry+https://github.com/rust-lang/crates.io-index"
274추가: checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa"
275추가: dependencies = [
276추가: "bitflags 2.13.2",
277추가: "cexpr",
278추가: "clang-sys",
279추가: "proc-macro2",
280추가: "quote",
281추가: "regex",
282추가: "rustc-hash 2.1.3",
283추가: "shlex",
284추가: "syn 3.0.10",
285추가: ]
286추가:
270287[[package]]
271288name = "bit-set"
272289version = "0.10.0"
@@ -424,6 +441,15 @@ dependencies = [
424441 "shlex",
425442]
426443
444추가: [[package]]
445추가: name = "cexpr"
446추가: version = "0.6.0"
447추가: source = "registry+https://github.com/rust-lang/crates.io-index"
448추가: checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
449추가: dependencies = [
450추가: "nom 7.1.3",
451추가: ]
452추가:
427453[[package]]
428454name = "cfg-if"
429455version = "1.0.5"
@@ -436,6 +462,17 @@ version = "0.2.2"
436462source = "registry+https://github.com/rust-lang/crates.io-index"
437463checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
438464
465추가: [[package]]
466추가: name = "clang-sys"
467추가: version = "1.9.1"
468추가: source = "registry+https://github.com/rust-lang/crates.io-index"
469추가: checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"
470추가: dependencies = [
471추가: "glob",
472추가: "libc",
473추가: "libloading",
474추가: ]
475추가:
439476[[package]]
440477name = "clipboard-win"
441478version = "5.4.3"
@@ -1015,6 +1052,31 @@ version = "0.4.1"
10151052source = "registry+https://github.com/rust-lang/crates.io-index"
10161053checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"
10171054
1055추가: [[package]]
1056추가: name = "ffmpeg-next"
1057추가: version = "9.1.0"
1058추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1059추가: checksum = "041fc1d1e9e6f62e03f52d8a2b1cc138d799defbaf7a9d69ddde78c97fb06e97"
1060추가: dependencies = [
1061추가: "bitflags 2.13.2",
1062추가: "ffmpeg-sys-next",
1063추가: "libc",
1064추가: ]
1065추가:
1066추가: [[package]]
1067추가: name = "ffmpeg-sys-next"
1068추가: version = "9.1.1"
1069추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1070추가: checksum = "226c264da7fce6bd034bfc0b20f87ce4ecc97b3294c407503557910c05e43588"
1071추가: dependencies = [
1072추가: "bindgen",
1073추가: "cc",
1074추가: "libc",
1075추가: "num_cpus",
1076추가: "pkg-config",
1077추가: "vcpkg",
1078추가: ]
1079추가:
10181080[[package]]
10191081name = "fiat-crypto"
10201082version = "0.3.0"
@@ -1195,6 +1257,12 @@ dependencies = [
11951257 "vello_common",
11961258]
11971259
1260추가: [[package]]
1261추가: name = "glob"
1262추가: version = "0.3.4"
1263추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1264추가: checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
1265추가:
11981266[[package]]
11991267name = "glow"
12001268version = "0.17.0"
@@ -1897,6 +1965,16 @@ dependencies = [
18971965 "libm",
18981966]
18991967
1968추가: [[package]]
1969추가: name = "num_cpus"
1970추가: version = "1.17.0"
1971추가: source = "registry+https://github.com/rust-lang/crates.io-index"
1972추가: checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
1973추가: dependencies = [
1974추가: "hermit-abi",
1975추가: "libc",
1976추가: ]
1977추가:
19001978[[package]]
19011979name = "num_enum"
19021980version = "0.7.6"
@@ -3449,6 +3527,12 @@ version = "1.29.3"
34493527source = "registry+https://github.com/rust-lang/crates.io-index"
34503528checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
34513529
3530추가: [[package]]
3531추가: name = "vcpkg"
3532추가: version = "0.2.15"
3533추가: source = "registry+https://github.com/rust-lang/crates.io-index"
3534추가: checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
3535추가:
34523536[[package]]
34533537name = "vello_common"
34543538version = "0.2.0"
@@ -3564,6 +3648,8 @@ dependencies = [
35643648 "egui-winit",
35653649 "egui_kittest",
35663650 "env_logger",
3651추가: "ffmpeg-next",
3652추가: "ffmpeg-sys-next",
35673653 "getrandom 0.4.3",
35683654 "image",
35693655 "log",
수정Cargo.toml+2-0
@@ -16,6 +16,8 @@ egui = "0.37.0"
1616egui-wgpu = { version = "0.37.0", features = ["winit", "wayland", "x11"] }
1717egui-winit = "0.37.0"
1818env_logger = "0.11.12"
19추가: ffmpeg-next = { version = "9.1.0", default-features = false, features = ["codec", "format", "software-scaling"] }
20추가: ffmpeg-sys-next = { version = "9.1.1", default-features = false, features = ["avcodec", "avformat", "swscale"] }
1921getrandom = "0.4.3"
2022log = "0.4.35"
2123pollster = "1.0.3"
수정android/app/src/main/java/com/androidremote/daemon/DaemonMain.kt+1-0
@@ -41,6 +41,7 @@ object DaemonMain {
4141 Log.i("인증서 SHA-256: ${Hex.encode(identity.fingerprint)}")
4242 Log.i("확인 코드: ${identity.confirmCode}, 새 PC 정책: $policy")
4343 SystemAccess.displaySize()?.let { (w, h) -> Log.i("디스플레이: ${w}x$h") }
44추가: Log.i("하드웨어 인코더: ${Encoders.hardware}")
4445
4546 Server(port, identity, whitelist, policy, DAEMON_VERSION).run()
4647 }
수정android/app/src/main/java/com/androidremote/daemon/Server.kt+46-24
@@ -33,12 +33,19 @@ class Server(
3333 private class Session(val token: ByteArray) {
3434 val videoAttached = AtomicBoolean(false)
3535 val closeables = mutableListOf<Closeable>()
36추가: /** 마지막 VIDEO_CONFIG. 영상 채널이 붙으면 이 설정으로 인코딩을 시작한다. */
37추가: @Volatile var videoConfig: Messages.VideoConfig? = null
38추가: @Volatile var streamer: VideoStreamer? = null
39추가: var configGen = 0
3640
3741 @Synchronized
3842 fun track(c: Closeable) = closeables.add(c)
3943
4044 @Synchronized
41삭제: fun closeAll() = closeables.forEach { runCatching { it.close() } }
45추가: fun closeAll() {
46추가: streamer?.stop()
47추가: closeables.forEach { runCatching { it.close() } }
48추가: }
4249 }
4350
4451 fun run() {
@@ -128,7 +135,7 @@ class Server(
128135 io.send(Protocol.MsgType.AUTH_RESULT, Messages.encodeAuthResult(
129136 Protocol.AuthResultCode.OK, grant, token, daemonVersion))
130137 Log.i("$peer: 인증 완료 grant=${if (grant == Protocol.Grant.ALWAYS) "ALWAYS" else "ONCE"}")
131삭제: serveControl(io, peer)
138추가: serveControl(io, peer, session)
132139 } finally {
133140 sessions.remove(Hex.encode(token))
134141 session.closeAll()
@@ -151,24 +158,26 @@ class Server(
151158 }
152159 }
153160
154삭제: private var configGen = 0
155삭제:
156삭제: private fun serveControl(io: FrameIO, peer: String) {
161추가: private fun serveControl(io: FrameIO, peer: String, session: Session) {
157162 while (true) {
158163 val f = io.read() ?: return
159164 try {
160165 when (f.type) {
161166 Protocol.MsgType.PING -> io.sendWithSeq(Protocol.MsgType.PONG, f.seq)
162167 Protocol.MsgType.PONG -> Unit
168추가: Protocol.MsgType.VIDEO_REQUEST_KEYFRAME -> session.streamer?.requestKeyframe()
163169 Protocol.MsgType.SYSTEM_ACTION -> handleSystemAction(Messages.decodeSystemAction(f.payload), peer)
164170 Protocol.MsgType.VIDEO_CONFIG_REQUEST -> {
165171 val req = Messages.decodeVideoConfigRequest(f.payload)
166삭제: val cfg = videoConfigFor(req)
172추가: val cfg = videoConfigFor(req, session)
167173 if (cfg == null) {
168삭제: io.sendError(Protocol.ErrorCode.INTERNAL, "지원하는 코덱이 없습니다")
174추가: io.sendError(Protocol.ErrorCode.INTERNAL, "지원하는 하드웨어 코덱이 없습니다")
169175 } else {
176추가: // 기획서 7.6: VIDEO_CONFIG 통지 후 영상 채널에 CONFIG -> KEYFRAME 순으로 보낸다.
170177 io.send(Protocol.MsgType.VIDEO_CONFIG, Messages.encodeVideoConfig(cfg))
171삭제: Log.i("$peer: VIDEO_CONFIG ${cfg.width}x${cfg.height} ${cfg.fps}fps codec=${cfg.codec}")
178추가: session.videoConfig = cfg
179추가: session.streamer?.reconfigure(cfg)
180추가: Log.i("$peer: VIDEO_CONFIG ${cfg.width}x${cfg.height} ${cfg.fps}fps codec=${cfg.codec} gen=${cfg.configGen}")
172181 }
173182 }
174183 else -> Log.i("$peer: 아직 처리하지 않는 메시지 0x%02x".format(f.type))
@@ -197,22 +206,19 @@ class Server(
197206 Log.i("$peer: SYSTEM_ACTION 0x%02x -> keycode $keycode".format(code))
198207 }
199208
200삭제: /** 1단계: 인코더 없이 기기 화면 크기로 영상 설정만 계산한다. 인코딩은 2단계에서 붙인다. */
201삭제: @Synchronized
202삭제: private fun videoConfigFor(req: Messages.VideoConfigRequest): Messages.VideoConfig? {
203삭제: val codec = when {
204삭제: req.codecMask and Protocol.Codec.H264 != 0 -> Protocol.Codec.H264
205삭제: req.codecMask and Protocol.Codec.H265 != 0 -> Protocol.Codec.H265
206삭제: else -> return null
207삭제: }
209추가: /** 요청과 기기 하드웨어 인코더로 실제 영상 설정을 정한다. 크기는 인코더 호환을 위해 16의 배수로 맞춘다. */
210추가: private fun videoConfigFor(req: Messages.VideoConfigRequest, session: Session): Messages.VideoConfig? {
211추가: val codec = Encoders.choose(req.codecMask) ?: return null
208212 val (dw, dh) = SystemAccess.displaySize() ?: (1080 to 2400)
209213 val long = maxOf(dw, dh)
210214 val scale = if (req.maxSize == 0 || req.maxSize >= long) 1.0 else req.maxSize.toDouble() / long
211삭제: val w = ((dw * scale).toInt()) and 1.inv()
212삭제: val h = ((dh * scale).toInt()) and 1.inv()
213삭제: configGen = (configGen % 255) + 1
215추가: val w = (dw * scale).toInt() and 15.inv()
216추가: val h = (dh * scale).toInt() and 15.inv()
214217 val fps = if (req.maxFps == 0) 60 else minOf(req.maxFps, 120)
215삭제: return Messages.VideoConfig(codec, configGen, w, h, fps, req.bitrate, dw, dh)
218추가: synchronized(session) {
219추가: session.configGen = (session.configGen % 255) + 1
220추가: return Messages.VideoConfig(codec, session.configGen, w, h, fps, req.bitrate, dw, dh)
221추가: }
216222 }
217223
218224 private fun handleVideo(socket: SSLSocket, first: Frame, peer: String) {
@@ -225,9 +231,25 @@ class Server(
225231 return
226232 }
227233 session.track(socket)
228삭제: Log.i("$peer: 영상 채널 연결 (인코더는 2단계에서 구현)")
229삭제: // 호스트는 영상 채널로 아무것도 보내지 않는다. 연결이 닫힐 때까지 기다린다.
230삭제: val buf = ByteArray(256)
231삭제: while (socket.inputStream.read(buf) >= 0) Unit
234추가: val config = session.videoConfig ?: videoConfigFor(
235추가: Messages.VideoConfigRequest(1920, 60, Protocol.Codec.H264 or Protocol.Codec.H265, 8_000_000), session,
236추가: )
237추가: if (config == null) {
238추가: Log.w("$peer: 하드웨어 인코더가 없어 영상 채널을 닫습니다")
239추가: return
240추가: }
241추가: session.videoConfig = config
242추가: val streamer = VideoStreamer(java.io.BufferedOutputStream(socket.outputStream, 256 * 1024), peer)
243추가: session.streamer = streamer
244추가: Log.i("$peer: 영상 채널 연결")
245추가: streamer.start(config)
246추가: try {
247추가: // 호스트는 영상 채널로 아무것도 보내지 않는다. 연결이 닫힐 때까지 기다린다.
248추가: val buf = ByteArray(256)
249추가: while (socket.inputStream.read(buf) >= 0) Unit
250추가: } finally {
251추가: streamer.stop()
252추가: session.streamer = null
253추가: }
232254 }
233255}
추가android/app/src/main/java/com/androidremote/daemon/VideoStreamer.kt+253-0
@@ -0,0 +1,253 @@
1추가: package com.androidremote.daemon
2추가:
3추가: import android.graphics.Rect
4추가: import android.hardware.display.DisplayManager
5추가: import android.hardware.display.VirtualDisplay
6추가: import android.media.MediaCodec
7추가: import android.media.MediaCodecInfo
8추가: import android.media.MediaCodecList
9추가: import android.media.MediaFormat
10추가: import android.os.Bundle
11추가: import android.os.IBinder
12추가: import android.view.Surface
13추가: import java.io.IOException
14추가: import java.io.OutputStream
15추가: import java.nio.ByteBuffer
16추가: import java.util.concurrent.ArrayBlockingQueue
17추가: import java.util.concurrent.TimeUnit
18추가:
19추가: /** 하드웨어 영상 인코더 목록 (기획서 7.6 "캡처와 인코딩"). */
20추가: object Encoders {
21추가: private fun mime(codec: Int) = when (codec) {
22추가: Protocol.Codec.H264 -> MediaFormat.MIMETYPE_VIDEO_AVC
23추가: Protocol.Codec.H265 -> MediaFormat.MIMETYPE_VIDEO_HEVC
24추가: Protocol.Codec.AV1 -> MediaFormat.MIMETYPE_VIDEO_AV1
25추가: else -> throw IllegalArgumentException("codec $codec")
26추가: }
27추가:
28추가: /** 코덱 비트 -> 하드웨어 인코더 이름. 소프트웨어 인코더는 지연이 커서 쓰지 않는다. */
29추가: val hardware: Map<Int, String> by lazy {
30추가: val found = LinkedHashMap<Int, String>()
31추가: val infos = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos
32추가: for (codec in intArrayOf(Protocol.Codec.AV1, Protocol.Codec.H265, Protocol.Codec.H264)) {
33추가: val m = mime(codec)
34추가: infos.firstOrNull { info ->
35추가: info.isEncoder && info.isHardwareAccelerated && !info.isSoftwareOnly &&
36추가: info.supportedTypes.any { it.equals(m, ignoreCase = true) }
37추가: }?.let { found[codec] = it.name }
38추가: }
39추가: found
40추가: }
41추가:
42추가: fun mimeOf(codec: Int) = mime(codec)
43추가:
44추가: /** 호스트 허용 목록과 기기 인코더가 겹치는 것 중 AV1, H.265, H.264 순으로 고른다. */
45추가: fun choose(hostMask: Int): Int? =
46추가: intArrayOf(Protocol.Codec.AV1, Protocol.Codec.H265, Protocol.Codec.H264)
47추가: .firstOrNull { hostMask and it != 0 && hardware.containsKey(it) }
48추가: }
49추가:
50추가: /**
51추가: * 기기 화면을 가상 디스플레이로 미러링해 MediaCodec으로 인코딩하고, 영상 채널에
52추가: * 16바이트 헤더 + Annex-B 데이터 형식으로 보낸다 (기획서 7.6).
53추가: *
54추가: * 인코더 스레드와 송신 스레드를 나누고, 송신 큐가 차면 비키프레임을 버린 뒤 키프레임을
55추가: * 요청해 지연이 쌓이지 않게 한다.
56추가: */
57추가: class VideoStreamer(private val output: OutputStream, private val peer: String) {
58추가: private class Packet(val ptsUs: Long, val flags: Int, val gen: Int, val data: ByteArray)
59추가:
60추가: private val queue = ArrayBlockingQueue<Packet>(QUEUE_LIMIT)
61추가: @Volatile private var running = true
62추가: @Volatile private var pending: Messages.VideoConfig? = null
63추가: @Volatile private var currentCodec: MediaCodec? = null
64추가: @Volatile private var waitingKeyframe = false
65추가: private var encoderThread: Thread? = null
66추가: private var writerThread: Thread? = null
67추가:
68추가: fun start(config: Messages.VideoConfig) {
69추가: pending = config
70추가: writerThread = Thread(::writeLoop, "video-writer").also { it.start() }
71추가: encoderThread = Thread(::encodeLoop, "video-encoder").also { it.start() }
72추가: }
73추가:
74추가: /** 해상도·비트레이트·코덱이 바뀌면 인코더를 다시 만든다. */
75추가: fun reconfigure(config: Messages.VideoConfig) {
76추가: pending = config
77추가: }
78추가:
79추가: fun requestKeyframe() {
80추가: val codec = currentCodec ?: return
81추가: try {
82추가: codec.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) })
83추가: } catch (e: IllegalStateException) {
84추가: // 인코더가 막 교체되는 중이면 무시한다. 새 인코더는 키프레임으로 시작한다.
85추가: }
86추가: }
87추가:
88추가: fun stop() {
89추가: running = false
90추가: encoderThread?.interrupt()
91추가: writerThread?.interrupt()
92추가: }
93추가:
94추가: private fun encodeLoop() {
95추가: try {
96추가: while (running) {
97추가: val config = pending ?: break
98추가: pending = null
99추가: runEncoder(config)
100추가: }
101추가: } catch (e: Exception) {
102추가: Log.w("$peer: 인코더 오류 $e")
103추가: } finally {
104추가: running = false
105추가: writerThread?.interrupt()
106추가: }
107추가: }
108추가:
109추가: private fun runEncoder(cfg: Messages.VideoConfig) {
110추가: val name = Encoders.hardware[cfg.codec] ?: throw IOException("하드웨어 인코더 없음: codec=${cfg.codec}")
111추가: val codec = MediaCodec.createByCodecName(name)
112추가: val format = MediaFormat.createVideoFormat(Encoders.mimeOf(cfg.codec), cfg.width, cfg.height).apply {
113추가: setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
114추가: setInteger(MediaFormat.KEY_BIT_RATE, cfg.bitrate.toInt())
115추가: setInteger(MediaFormat.KEY_FRAME_RATE, cfg.fps)
116추가: setFloat(MediaFormat.KEY_MAX_FPS_TO_ENCODER, cfg.fps.toFloat())
117추가: setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, KEYFRAME_INTERVAL_S)
118추가: // 화면 변화가 없어도 마지막 프레임을 다시 보내 정지 화면처럼 보이지 않게 한다.
119추가: setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_AFTER_US)
120추가: setInteger(MediaFormat.KEY_PRIORITY, 0)
121추가: setInteger(MediaFormat.KEY_MAX_B_FRAMES, 0)
122추가: setInteger(MediaFormat.KEY_LATENCY, 1)
123추가: val caps = codec.codecInfo.getCapabilitiesForType(Encoders.mimeOf(cfg.codec))
124추가: if (caps.encoderCapabilities.isBitrateModeSupported(
125추가: MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)) {
126추가: setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)
127추가: }
128추가: }
129추가: codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
130추가: val surface = codec.createInputSurface()
131추가: val display = DisplayCapture.mirror("android-remote", cfg.width, cfg.height, cfg.displayWidth, cfg.displayHeight, surface)
132추가: codec.start()
133추가: currentCodec = codec
134추가: waitingKeyframe = false
135추가: Log.i("$peer: 인코딩 시작 $name ${cfg.width}x${cfg.height} ${cfg.fps}fps ${cfg.bitrate / 1000}kbps gen=${cfg.configGen} (${display.method})")
136추가:
137추가: val info = MediaCodec.BufferInfo()
138추가: try {
139추가: while (running && pending == null) {
140추가: val index = codec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT_US)
141추가: if (index < 0) continue
142추가: val buf: ByteBuffer = codec.getOutputBuffer(index) ?: run {
143추가: codec.releaseOutputBuffer(index, false)
144추가: continue
145추가: }
146추가: if (info.size > 0) {
147추가: val data = ByteArray(info.size)
148추가: buf.position(info.offset)
149추가: buf.get(data, 0, info.size)
150추가: val isConfig = info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0
151추가: val isKey = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
152추가: var flags = 0
153추가: if (isConfig) flags = flags or FLAG_CONFIG
154추가: if (isKey) flags = flags or FLAG_KEYFRAME
155추가: enqueue(Packet(if (isConfig) 0 else info.presentationTimeUs, flags, cfg.configGen, data))
156추가: }
157추가: codec.releaseOutputBuffer(index, false)
158추가: }
159추가: } finally {
160추가: currentCodec = null
161추가: runCatching { codec.stop() }
162추가: runCatching { codec.release() }
163추가: display.release()
164추가: surface.release()
165추가: }
166추가: }
167추가:
168추가: /** 송신이 밀리면 비키프레임을 버리고 다음 키프레임까지 기다린다 (지연 우선). */
169추가: private fun enqueue(p: Packet) {
170추가: val important = p.flags and (FLAG_CONFIG or FLAG_KEYFRAME) != 0
171추가: if (important) {
172추가: if (p.flags and FLAG_KEYFRAME != 0) waitingKeyframe = false
173추가: queue.put(p)
174추가: return
175추가: }
176추가: if (waitingKeyframe) return
177추가: if (!queue.offer(p)) {
178추가: waitingKeyframe = true
179추가: requestKeyframe()
180추가: }
181추가: }
182추가:
183추가: private fun writeLoop() {
184추가: val header = ByteBuffer.allocate(Protocol.VIDEO_HEADER_LEN)
185추가: try {
186추가: while (running) {
187추가: val p = queue.poll(200, TimeUnit.MILLISECONDS) ?: continue
188추가: header.clear()
189추가: header.putLong(p.ptsUs).put(p.flags.toByte()).put(p.gen.toByte()).putShort(0).putInt(p.data.size)
190추가: output.write(header.array())
191추가: output.write(p.data)
192추가: output.flush()
193추가: }
194추가: } catch (e: InterruptedException) {
195추가: // 정상 종료
196추가: } catch (e: IOException) {
197추가: Log.i("$peer: 영상 송신 종료 (${e.message})")
198추가: } finally {
199추가: running = false
200추가: encoderThread?.interrupt()
201추가: }
202추가: }
203추가:
204추가: companion object {
205추가: const val FLAG_CONFIG = 0x01
206추가: const val FLAG_KEYFRAME = 0x02
207추가: private const val QUEUE_LIMIT = 4
208추가: private const val KEYFRAME_INTERVAL_S = 10
209추가: private const val REPEAT_AFTER_US = 100_000L
210추가: private const val DEQUEUE_TIMEOUT_US = 50_000L
211추가: }
212추가: }
213추가:
214추가: /**
215추가: * 기본 디스플레이(0)를 인코더 입력 Surface로 미러링한다. Android 14+의 숨은
216추가: * DisplayManager.createVirtualDisplay(이름, 너비, 높이, 미러링할 디스플레이, Surface)를 먼저 쓰고,
217추가: * 실패하면 SurfaceControl 방식으로 대체한다.
218추가: */
219추가: object DisplayCapture {
220추가: class Handle(val method: String, private val onRelease: () -> Unit) {
221추가: fun release() = runCatching { onRelease() }.let { }
222추가: }
223추가:
224추가: fun mirror(name: String, width: Int, height: Int, displayWidth: Int, displayHeight: Int, surface: Surface): Handle {
225추가: try {
226추가: val m = DisplayManager::class.java.getMethod(
227추가: "createVirtualDisplay",
228추가: String::class.java, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType,
229추가: Int::class.javaPrimitiveType, Surface::class.java,
230추가: )
231추가: val vd = m.invoke(null, name, width, height, 0, surface) as VirtualDisplay
232추가: return Handle("DisplayManager") { vd.release() }
233추가: } catch (e: Exception) {
234추가: Log.w("DisplayManager 미러링 실패, SurfaceControl로 대체: ${e.cause ?: e}")
235추가: }
236추가:
237추가: val sc = Class.forName("android.view.SurfaceControl")
238추가: val token = sc.getMethod("createDisplay", String::class.java, Boolean::class.javaPrimitiveType)
239추가: .invoke(null, name, false) as IBinder
240추가: sc.getMethod("openTransaction").invoke(null)
241추가: try {
242추가: sc.getMethod("setDisplaySurface", IBinder::class.java, Surface::class.java).invoke(null, token, surface)
243추가: sc.getMethod("setDisplayProjection", IBinder::class.java, Int::class.javaPrimitiveType, Rect::class.java, Rect::class.java)
244추가: .invoke(null, token, 0, Rect(0, 0, displayWidth, displayHeight), Rect(0, 0, width, height))
245추가: sc.getMethod("setDisplayLayerStack", IBinder::class.java, Int::class.javaPrimitiveType).invoke(null, token, 0)
246추가: } finally {
247추가: sc.getMethod("closeTransaction").invoke(null)
248추가: }
249추가: return Handle("SurfaceControl") {
250추가: sc.getMethod("destroyDisplay", IBinder::class.java).invoke(null, token)
251추가: }
252추가: }
253추가: }
수정examples/probe.rs+55-6
@@ -1,6 +1,8 @@
11//! 기기 연결 점검 도구. GUI 없이 접속, 인증, PING 왕복, 영상 설정, 시스템 버튼을 확인한다.
22//!
3삭제: //! `cargo run --example probe -- 127.0.0.1:27200 [--key back|home|recents]`
3추가: //! `cargo run --example probe -- 127.0.0.1:27200 [--key back|home|recents] [--record out.h264 --seconds 3]`
4추가: //!
5추가: //! `--record`를 주면 영상 채널로 받은 Annex-B 스트림을 파일로 저장한다(ffprobe/ffplay로 확인).
46//!
57//! GUI와 같은 PC 키(`~/.config/android-remote/device_key`)와 기기 지문 목록을 쓰므로,
68//! 여기서 허용된 PC는 GUI에서도 승인 없이 연결된다.
@@ -84,16 +86,63 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
8486 println!("SYSTEM_ACTION {action:?} 전송");
8587 }
8688
89추가: let record = option(&args, "--record");
90추가: let seconds: u64 = option(&args, "--seconds")
91추가: .and_then(|s| s.parse().ok())
92추가: .unwrap_or(3);
8793 let mut video = session.open_video(Duration::from_secs(5)).await?;
88삭제: match tokio::time::timeout(Duration::from_millis(500), video.read_packet()).await {
89삭제: Err(_) => println!("영상 채널 연결됨 (아직 영상 없음)"),
90삭제: Ok(Ok((h, data))) => println!("영상 패킷 수신: {h:?} {}바이트", data.len()),
91삭제: Ok(Err(FramedError::Closed)) => println!("영상 채널이 바로 닫혔습니다"),
92삭제: Ok(Err(e)) => println!("영상 채널 오류: {e}"),
94추가: let opened = Instant::now();
95추가: let mut file = record.map(std::fs::File::create).transpose()?;
96추가: let (mut frames, mut bytes, mut keyframes) = (0u64, 0u64, 0u64);
97추가: let mut first_frame = None;
98추가: let deadline = opened + Duration::from_secs(seconds);
99추가: loop {
100추가: let left = deadline.saturating_duration_since(Instant::now());
101추가: if left.is_zero() {
102추가: break;
103추가: }
104추가: match tokio::time::timeout(left, video.read_packet()).await {
105추가: Err(_) => break,
106추가: Ok(Ok((h, data))) => {
107추가: if let Some(f) = file.as_mut() {
108추가: std::io::Write::write_all(f, &data)?;
109추가: }
110추가: if h.is_config {
111추가: println!("CONFIG 패킷 gen={} {}바이트", h.config_gen, data.len());
112추가: continue;
113추가: }
114추가: first_frame.get_or_insert_with(|| opened.elapsed());
115추가: frames += 1;
116추가: bytes += data.len() as u64;
117추가: keyframes += u64::from(h.is_keyframe);
118추가: }
119추가: Ok(Err(FramedError::Closed)) => {
120추가: println!("영상 채널이 닫혔습니다");
121추가: break;
122추가: }
123추가: Ok(Err(e)) => {
124추가: println!("영상 채널 오류: {e}");
125추가: break;
126추가: }
127추가: }
93128 }
129추가: let secs = seconds as f64;
130추가: println!(
131추가: "영상: 첫 프레임까지 {:?}, {frames}프레임({:.1}fps), 키프레임 {keyframes}, 평균 {:.2} Mbps",
132추가: first_frame,
133추가: frames as f64 / secs,
134추가: bytes as f64 * 8.0 / secs / 1e6
135추가: );
94136 Ok(())
95137}
96138
139추가: fn option<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
140추가: args.iter()
141추가: .position(|a| a == name)
142추가: .and_then(|i| args.get(i + 1))
143추가: .map(String::as_str)
144추가: }
145추가:
97146fn wayland_android_remote_target(s: &str) -> Result<std::net::SocketAddr, String> {
98147 if let Ok(a) = s.parse() {
99148 return Ok(a);
수정src/lib.rs+1-0
@@ -5,3 +5,4 @@
55pub mod config;
66pub mod net;
77pub mod protocol;
8추가: pub mod video;
수정src/main.rs+3-1
@@ -2,7 +2,9 @@ mod ui;
22
33fn main() {
44 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
5삭제: if let Err(e) = ui::run() {
5추가: // `android-remote 192.168.0.12` 처럼 주소를 주면 시작하자마자 연결한다.
6추가: let target = std::env::args().nth(1);
7추가: if let Err(e) = ui::run(target) {
68 log::error!("{e}");
79 std::process::exit(1);
810 }
수정src/ui/conn.rs+197-17
@@ -14,8 +14,26 @@ use wayland_android_remote::net::{
1414 ConnectError, ConnectEvent, ConnectOptions, FramedError, HostIdentity, KnownDevices, connect,
1515};
1616use wayland_android_remote::protocol::{
17삭제: AuthGrant, CodecMask, Message, SystemAction, VideoConfig, VideoConfigRequest,
17추가: AuthGrant, CodecMask, Message, SystemAction, VideoCodec, VideoConfig, VideoConfigRequest,
18추가: VideoPacketHeader,
1819};
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추가: }
1937
2038/// UI에 알리는 연결 상태 변화.
2139#[derive(Debug, Clone)]
@@ -53,6 +71,7 @@ pub struct Connector {
5371/// 진행 중인 연결 하나. 버리면 연결을 끊는다.
5472pub struct ConnHandle {
5573 pub events: mpsc::Receiver<ConnEvent>,
74추가: pub frames: Arc<FrameSlot>,
5675 commands: tmpsc::UnboundedSender<ConnCommand>,
5776 task: JoinHandle<()>,
5877}
@@ -76,6 +95,8 @@ impl Connector {
7695 .thread_name("android-remote-net")
7796 .enable_all()
7897 .build()?;
98추가: // FFmpeg가 stderr로 내는 VA-API 탐색·손상 프레임 경고를 줄인다.
99추가: ffmpeg_next::util::log::set_level(ffmpeg_next::util::log::Level::Error);
79100 let identity = match HostIdentity::default_path() {
80101 Some(path) => HostIdentity::load_or_create(&path).unwrap_or_else(|e| {
81102 log::error!(
@@ -101,6 +122,7 @@ impl Connector {
101122 tx,
102123 waker: self.waker.clone(),
103124 };
125추가: let frames = Arc::new(FrameSlot::default());
104126 let task = self.runtime.spawn(run(
105127 target,
106128 self.identity.clone(),
@@ -108,9 +130,11 @@ impl Connector {
108130 video,
109131 emit,
110132 cmd_rx,
133추가: frames.clone(),
111134 ));
112135 ConnHandle {
113136 events: rx,
137추가: frames,
114138 commands: cmd_tx,
115139 task,
116140 }
@@ -146,6 +170,7 @@ async fn run(
146170 video: VideoConfigRequest,
147171 emit: Emitter,
148172 mut commands: tmpsc::UnboundedReceiver<ConnCommand>,
173추가: frames: Arc<FrameSlot>,
149174) {
150175 let pinned = known
151176 .lock()
@@ -186,25 +211,36 @@ async fn run(
186211 grant: session.grant,
187212 });
188213
189삭제: if let Err(e) = session
190삭제: .control()
191삭제: .send(&Message::VideoConfigRequest(video))
192삭제: .await
193삭제: {
194삭제: emit.emit(ConnEvent::Ended(format!("연결이 끊겼습니다: {e}")));
195삭제: return;
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}");
196235 }
197236
198삭제: // 영상 채널: 디코더가 붙기 전까지는 수신 프레임 수만 센다.
199237 let video_task = match session.open_video(Duration::from_secs(5)).await {
200238 Ok(mut stream) => {
201삭제: let emit = emit.clone();
239추가: let dec_tx = dec_tx.clone();
202240 Some(tokio::spawn(async move {
203삭제: let mut frames = 0u64;
204삭제: while let Ok((header, _data)) = stream.read_packet().await {
205삭제: if !header.is_config {
206삭제: frames += 1;
207삭제: emit.emit(ConnEvent::VideoFrames(frames));
241추가: while let Ok((header, data)) = stream.read_packet().await {
242추가: if dec_tx.send(DecoderInput::Packet(header, data)).is_err() {
243추가: break;
208244 }
209245 }
210246 }))
@@ -215,18 +251,154 @@ async fn run(
215251 }
216252 };
217253
218삭제: let reason = control_loop(session.control(), &mut commands, &emit).await;
254추가: let reason = control_loop(
255추가: session.control(),
256추가: &mut commands,
257추가: &mut keyframe_rx,
258추가: &dec_tx,
259추가: &emit,
260추가: )
261추가: .await;
219262 if let Some(t) = video_task {
220263 t.abort();
221264 }
265추가: // dec_tx가 사라지면 디코더 스레드도 끝난다.
266추가: drop(dec_tx);
222267 emit.emit(ConnEvent::Ended(reason));
223268}
224269
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추가:
225395async fn control_loop(
226396 control: &mut wayland_android_remote::net::FramedStream<
227397 wayland_android_remote::net::DeviceStream,
228398 >,
229399 commands: &mut tmpsc::UnboundedReceiver<ConnCommand>,
400추가: keyframe: &mut tmpsc::UnboundedReceiver<()>,
401추가: decoder: &mpsc::Sender<DecoderInput>,
230402 emit: &Emitter,
231403) -> String {
232404 let mut ping = tokio::time::interval(Duration::from_secs(2));
@@ -238,7 +410,10 @@ async fn control_loop(
238410 return format!("연결이 끊겼습니다: {e}");
239411 }
240412 }
241삭제: Ok((_, Message::VideoConfig(cfg))) => emit.emit(ConnEvent::VideoConfig(cfg)),
413추가: Ok((_, Message::VideoConfig(cfg))) => {
414추가: let _ = decoder.send(DecoderInput::Codec(cfg.codec));
415추가: emit.emit(ConnEvent::VideoConfig(cfg));
416추가: }
242417 Ok((_, Message::Error(e))) => log::warn!("기기 오류: {:#06x} {}", e.code, e.reason),
243418 Ok((_, other)) => log::debug!("처리하지 않은 메시지: {:?}", other.msg_type()),
244419 Err(FramedError::Closed) => return "기기가 연결을 닫았습니다".to_owned(),
@@ -254,6 +429,11 @@ async fn control_loop(
254429 return format!("연결이 끊겼습니다: {e}");
255430 }
256431 }
432추가: Some(()) = keyframe.recv() => {
433추가: if let Err(e) = control.send(&Message::VideoRequestKeyframe).await {
434추가: return format!("연결이 끊겼습니다: {e}");
435추가: }
436추가: }
257437 _ = ping.tick() => {
258438 if let Err(e) = control.send(&Message::Ping).await {
259439 return format!("연결이 끊겼습니다: {e}");
수정src/ui/mod.rs+27-4
@@ -13,6 +13,7 @@ mod layout;
1313mod recent;
1414#[cfg(test)]
1515mod snapshots;
16추가: mod video_render;
1617mod view;
1718
1819use std::num::NonZeroU32;
@@ -40,13 +41,14 @@ use view::{Actions, View};
4041struct Wake;
4142
4243/// 이벤트 루프를 만들고 창이 닫힐 때까지 실행한다.
43삭제: pub fn run() -> Result<(), Box<dyn std::error::Error>> {
44추가: pub fn run(autoconnect: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
4445 let event_loop = EventLoop::<Wake>::with_user_event().build()?;
4546 let proxy = event_loop.create_proxy();
4647 let connector = Connector::new(Arc::new(move || {
4748 let _ = proxy.send_event(Wake);
4849 }))?;
4950 let mut app = App::new(connector);
51추가: app.autoconnect = autoconnect;
5052 event_loop.run_app(&mut app)?;
5153 Ok(())
5254}
@@ -156,6 +158,8 @@ struct App {
156158 settings: Option<Gfx>,
157159 connector: Connector,
158160 conn: Option<ConnHandle>,
161추가: /// 시작 인자로 받은 접속 주소. 창이 뜬 뒤 한 번 연결한다.
162추가: autoconnect: Option<String>,
159163}
160164
161165impl App {
@@ -166,6 +170,7 @@ impl App {
166170 settings: None,
167171 connector,
168172 conn: None,
173추가: autoconnect: None,
169174 }
170175 }
171176
@@ -181,7 +186,14 @@ impl App {
181186 let gfx = Gfx::new(event_loop, attrs, WgpuSetup::CreateNew(setup))?;
182187 if let Some(rs) = gfx.painter.render_state() {
183188 let info = rs.adapter.get_info();
184삭제: log::info!("GPU: {} ({:?})", info.name, info.backend);
189추가: log::info!(
190추가: "GPU: {} ({:?}), 출력 형식 {:?}",
191추가: info.name,
192추가: info.backend,
193추가: rs.target_format
194추가: );
195추가: let pipeline = video_render::VideoPipeline::new(&rs.device, rs.target_format);
196추가: rs.renderer.write().callback_resources.insert(pipeline);
185197 }
186198 Ok(gfx)
187199 }
@@ -221,9 +233,13 @@ impl App {
221233 self.view.on_conn_event(event);
222234 if ended {
223235 self.conn = None;
224삭제: break;
236추가: return;
225237 }
226238 }
239추가: // 연결 상태 이벤트를 먼저 반영해야 첫 프레임이 버려지지 않는다.
240추가: if let Some(frame) = conn.frames.take() {
241추가: self.view.set_video_frame(frame);
242추가: }
227243 }
228244
229245 fn redraw(&mut self, kind: Kind, event_loop: &ActiveEventLoop) {
@@ -311,7 +327,14 @@ impl ApplicationHandler<Wake> for App {
311327 return;
312328 }
313329 match self.init_main(event_loop) {
314삭제: Ok(gfx) => self.main = Some(gfx),
330추가: Ok(gfx) => {
331추가: self.main = Some(gfx);
332추가: if let Some(target) = self.autoconnect.take() {
333추가: let mut actions = Actions::default();
334추가: self.view.request_connect(&target, &mut actions);
335추가: self.apply(actions, event_loop);
336추가: }
337추가: }
315338 Err(e) => {
316339 log::error!("창 또는 GPU 초기화 실패: {e}");
317340 event_loop.exit();
수정src/ui/snapshots.rs+115-0
@@ -73,3 +73,118 @@ fn snapshots() {
7373 view.settings_ui(ui, &mut Actions::default())
7474 });
7575}
76추가:
77추가: /// ffmpeg CLI로 영상 파일의 첫 프레임을 원시 YUV로 꺼낸다.
78추가: fn first_frame_yuv(path: &std::path::Path, nv12: bool) -> Option<super::video_render::YuvFrame> {
79추가: let probe = std::process::Command::new("ffprobe")
80추가: .args(["-v", "error", "-select_streams", "v:0", "-show_entries"])
81추가: .args(["stream=width,height", "-of", "csv=p=0"])
82추가: .arg(path)
83추가: .output()
84추가: .ok()?;
85추가: let dims = String::from_utf8(probe.stdout).ok()?;
86추가: let mut it = dims.trim().split(',');
87추가: let (w, h): (u32, u32) = (it.next()?.parse().ok()?, it.next()?.parse().ok()?);
88추가: let out = std::process::Command::new("ffmpeg")
89추가: .args(["-v", "error", "-i"])
90추가: .arg(path)
91추가: .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt"])
92추가: .arg(if nv12 { "nv12" } else { "yuv420p" })
93추가: .arg("-")
94추가: .output()
95추가: .ok()?;
96추가: let data = out.stdout;
97추가: let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
98추가: let y_len = (w * h) as usize;
99추가: let c_len = (cw * ch) as usize;
100추가: let planes = if nv12 {
101추가: vec![
102추가: (data[..y_len].to_vec(), w as usize, w, h),
103추가: (
104추가: data[y_len..y_len + 2 * c_len].to_vec(),
105추가: 2 * cw as usize,
106추가: cw,
107추가: ch,
108추가: ),
109추가: ]
110추가: } else {
111추가: vec![
112추가: (data[..y_len].to_vec(), w as usize, w, h),
113추가: (data[y_len..y_len + c_len].to_vec(), cw as usize, cw, ch),
114추가: (
115추가: data[y_len + c_len..y_len + 2 * c_len].to_vec(),
116추가: cw as usize,
117추가: cw,
118추가: ch,
119추가: ),
120추가: ]
121추가: };
122추가: Some(super::video_render::YuvFrame {
123추가: width: w,
124추가: height: h,
125추가: nv12,
126추가: planes,
127추가: bt709: true,
128추가: full_range: false,
129추가: })
130추가: }
131추가:
132추가: /// 영상 렌더러(YUV 셰이더)로 휴대폰 화면 영역에 프레임을 그린다.
133추가: /// `ANDROID_REMOTE_SNAPSHOT_VIDEO`에 녹화 파일을 주면 그 첫 프레임을, 없으면 ffmpeg 테스트 화면을 쓴다.
134추가: #[test]
135추가: #[ignore = "GPU와 ffmpeg가 필요한 시각 확인용"]
136추가: fn video_snapshots() {
137추가: use egui_kittest::wgpu::{WgpuTestRenderer, create_render_state, default_wgpu_setup};
138추가:
139추가: let source = match std::env::var_os("ANDROID_REMOTE_SNAPSHOT_VIDEO") {
140추가: Some(p) => PathBuf::from(p),
141추가: None => {
142추가: let p = out_dir().join("testsrc.h264");
143추가: let ok = std::process::Command::new("ffmpeg")
144추가: .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
145추가: .arg("testsrc2=size=864x1920:rate=1")
146추가: .args(["-frames:v", "1", "-c:v", "libx264", "-pix_fmt", "yuv420p"])
147추가: .args(["-color_range", "tv", "-colorspace", "bt709"])
148추가: .arg(&p)
149추가: .status()
150추가: .is_ok_and(|s| s.success());
151추가: assert!(ok, "ffmpeg로 테스트 영상을 만들지 못했습니다");
152추가: p
153추가: }
154추가: };
155추가:
156추가: for nv12 in [true, false] {
157추가: let frame = first_frame_yuv(&source, nv12).expect("프레임 추출 실패");
158추가: let render_state = create_render_state(default_wgpu_setup(), Default::default());
159추가: let pipeline = super::video_render::VideoPipeline::new(
160추가: &render_state.device,
161추가: render_state.target_format,
162추가: );
163추가: render_state
164추가: .renderer
165추가: .write()
166추가: .callback_resources
167추가: .insert(pipeline);
168추가:
169추가: let mut view = View::for_test();
170추가: view.start_connecting_for_test("192.168.0.12:27200".parse().unwrap());
171추가: view.on_conn_event(ConnEvent::Connected {
172추가: grant: AuthGrant::Always,
173추가: });
174추가: view.set_video_frame(std::sync::Arc::new(frame));
175추가: let size = view.window_size();
176추가: let mut harness = Harness::builder()
177추가: .with_size(size)
178추가: .with_accessibility_check(false)
179추가: .with_context_setup(|ctx| {
180추가: ctx.set_visuals(egui::Visuals::dark());
181추가: fonts::install_korean_font(ctx);
182추가: })
183추가: .renderer(WgpuTestRenderer::from_render_state(render_state))
184추가: .build_ui(|ui| view.ui(ui, &mut Actions::default()));
185추가: harness.run();
186추가: let image = harness.render().expect("렌더링 실패");
187추가: let name = if nv12 { "video_nv12" } else { "video_i420" };
188추가: image.save(out_dir().join(format!("{name}.png"))).unwrap();
189추가: }
190추가: }
추가src/ui/video_render.rs+359-0
@@ -0,0 +1,359 @@
1추가: //! 디코딩된 YUV 프레임을 GPU 텍스처로 올려 셰이더에서 RGB로 바꿔 그린다 (기획서 7.6 "표시").
2추가: //!
3추가: //! CPU에서 색 변환하거나 RGBA로 복사하지 않는다. Y와 U/V(또는 NV12의 UV) 평면을 그대로
4추가: //! 텍스처에 쓰고, egui 렌더 패스 안의 paint callback으로 휴대폰 화면 영역에 그린다.
5추가:
6추가: use std::sync::Arc;
7추가:
8추가: use egui_wgpu::wgpu;
9추가: use egui_wgpu::{CallbackResources, CallbackTrait, ScreenDescriptor};
10추가:
11추가: /// 렌더러가 받는 프레임. 디코더 출력에서 만든다.
12추가: pub struct YuvFrame {
13추가: pub width: u32,
14추가: pub height: u32,
15추가: /// true면 NV12(Y + 교차 UV), false면 I420(Y, U, V).
16추가: pub nv12: bool,
17추가: /// (데이터, 한 줄 바이트 수, 너비, 높이). I420은 3개, NV12는 2개.
18추가: pub planes: Vec<(Vec<u8>, usize, u32, u32)>,
19추가: pub bt709: bool,
20추가: pub full_range: bool,
21추가: }
22추가:
23추가: #[repr(C)]
24추가: #[derive(Clone, Copy)]
25추가: struct Params {
26추가: nv12: u32,
27추가: full_range: u32,
28추가: bt709: u32,
29추가: /// 대상 표면이 sRGB 형식이면 셰이더 출력에서 감마를 되돌린다.
30추가: srgb_target: u32,
31추가: }
32추가:
33추가: impl Params {
34추가: fn bytes(&self) -> [u8; 16] {
35추가: let mut out = [0u8; 16];
36추가: for (i, v) in [self.nv12, self.full_range, self.bt709, self.srgb_target]
37추가: .into_iter()
38추가: .enumerate()
39추가: {
40추가: out[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
41추가: }
42추가: out
43추가: }
44추가: }
45추가:
46추가: const SHADER: &str = r#"
47추가: struct Params { nv12: u32, full_range: u32, bt709: u32, srgb_target: u32 };
48추가: @group(0) @binding(0) var samp: sampler;
49추가: @group(0) @binding(1) var tex_y: texture_2d<f32>;
50추가: @group(0) @binding(2) var tex_u: texture_2d<f32>;
51추가: @group(0) @binding(3) var tex_v: texture_2d<f32>;
52추가: @group(0) @binding(4) var<uniform> params: Params;
53추가:
54추가: struct VsOut { @builtin(position) pos: vec4<f32>, @location(0) uv: vec2<f32> };
55추가:
56추가: @vertex fn vs_main(@builtin(vertex_index) i: u32) -> VsOut {
57추가: var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
58추가: let xy = p[i];
59추가: var o: VsOut;
60추가: o.pos = vec4(xy, 0.0, 1.0);
61추가: o.uv = vec2((xy.x + 1.0) * 0.5, 1.0 - (xy.y + 1.0) * 0.5);
62추가: return o;
63추가: }
64추가:
65추가: fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
66추가: let lo = c / 12.92;
67추가: let hi = pow((c + 0.055) / 1.055, vec3(2.4));
68추가: return select(hi, lo, c <= vec3(0.04045));
69추가: }
70추가:
71추가: @fragment fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
72추가: let y = textureSample(tex_y, samp, in.uv).r;
73추가: var u: f32;
74추가: var v: f32;
75추가: if (params.nv12 == 1u) {
76추가: let uv = textureSample(tex_u, samp, in.uv).rg;
77추가: u = uv.x;
78추가: v = uv.y;
79추가: } else {
80추가: u = textureSample(tex_u, samp, in.uv).r;
81추가: v = textureSample(tex_v, samp, in.uv).r;
82추가: }
83추가: var yy = y;
84추가: var cb = u - 0.5;
85추가: var cr = v - 0.5;
86추가: if (params.full_range == 0u) {
87추가: yy = (y - 16.0 / 255.0) * (255.0 / 219.0);
88추가: cb = (u - 128.0 / 255.0) * (255.0 / 224.0);
89추가: cr = (v - 128.0 / 255.0) * (255.0 / 224.0);
90추가: }
91추가: var rgb: vec3<f32>;
92추가: if (params.bt709 == 1u) {
93추가: rgb = vec3(yy + 1.5748 * cr, yy - 0.1873 * cb - 0.4681 * cr, yy + 1.8556 * cb);
94추가: } else {
95추가: rgb = vec3(yy + 1.402 * cr, yy - 0.3441 * cb - 0.7141 * cr, yy + 1.772 * cb);
96추가: }
97추가: rgb = clamp(rgb, vec3(0.0), vec3(1.0));
98추가: if (params.srgb_target == 1u) {
99추가: rgb = srgb_to_linear(rgb);
100추가: }
101추가: return vec4(rgb, 1.0);
102추가: }
103추가: "#;
104추가:
105추가: /// 렌더 파이프라인과 현재 텍스처. egui-wgpu의 `callback_resources`에 한 번 넣어 둔다.
106추가: pub struct VideoPipeline {
107추가: pipeline: wgpu::RenderPipeline,
108추가: layout: wgpu::BindGroupLayout,
109추가: sampler: wgpu::Sampler,
110추가: params: wgpu::Buffer,
111추가: srgb_target: bool,
112추가: textures: Option<Textures>,
113추가: /// 마지막으로 GPU에 올린 프레임 번호.
114추가: uploaded: Option<u64>,
115추가: }
116추가:
117추가: struct Textures {
118추가: key: (u32, u32, bool),
119추가: planes: Vec<wgpu::Texture>,
120추가: bind_group: wgpu::BindGroup,
121추가: }
122추가:
123추가: impl VideoPipeline {
124추가: pub fn new(device: &wgpu::Device, target: wgpu::TextureFormat) -> Self {
125추가: let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
126추가: label: Some("video-yuv"),
127추가: source: wgpu::ShaderSource::Wgsl(SHADER.into()),
128추가: });
129추가: let tex_entry = |binding| wgpu::BindGroupLayoutEntry {
130추가: binding,
131추가: visibility: wgpu::ShaderStages::FRAGMENT,
132추가: ty: wgpu::BindingType::Texture {
133추가: sample_type: wgpu::TextureSampleType::Float { filterable: true },
134추가: view_dimension: wgpu::TextureViewDimension::D2,
135추가: multisampled: false,
136추가: },
137추가: count: None,
138추가: };
139추가: let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
140추가: label: Some("video-yuv"),
141추가: entries: &[
142추가: wgpu::BindGroupLayoutEntry {
143추가: binding: 0,
144추가: visibility: wgpu::ShaderStages::FRAGMENT,
145추가: ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
146추가: count: None,
147추가: },
148추가: tex_entry(1),
149추가: tex_entry(2),
150추가: tex_entry(3),
151추가: wgpu::BindGroupLayoutEntry {
152추가: binding: 4,
153추가: visibility: wgpu::ShaderStages::FRAGMENT,
154추가: ty: wgpu::BindingType::Buffer {
155추가: ty: wgpu::BufferBindingType::Uniform,
156추가: has_dynamic_offset: false,
157추가: min_binding_size: None,
158추가: },
159추가: count: None,
160추가: },
161추가: ],
162추가: });
163추가: let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
164추가: label: Some("video-yuv"),
165추가: bind_group_layouts: &[Some(&layout)],
166추가: immediate_size: 0,
167추가: });
168추가: let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
169추가: label: Some("video-yuv"),
170추가: layout: Some(&pipeline_layout),
171추가: vertex: wgpu::VertexState {
172추가: module: &shader,
173추가: entry_point: Some("vs_main"),
174추가: compilation_options: Default::default(),
175추가: buffers: &[],
176추가: },
177추가: fragment: Some(wgpu::FragmentState {
178추가: module: &shader,
179추가: entry_point: Some("fs_main"),
180추가: compilation_options: Default::default(),
181추가: targets: &[Some(wgpu::ColorTargetState {
182추가: format: target,
183추가: blend: None,
184추가: write_mask: wgpu::ColorWrites::ALL,
185추가: })],
186추가: }),
187추가: primitive: wgpu::PrimitiveState::default(),
188추가: depth_stencil: None,
189추가: multisample: wgpu::MultisampleState::default(),
190추가: multiview_mask: None,
191추가: cache: None,
192추가: });
193추가: let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
194추가: label: Some("video-yuv"),
195추가: mag_filter: wgpu::FilterMode::Linear,
196추가: min_filter: wgpu::FilterMode::Linear,
197추가: ..Default::default()
198추가: });
199추가: let params = device.create_buffer(&wgpu::BufferDescriptor {
200추가: label: Some("video-yuv-params"),
201추가: size: 16,
202추가: usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
203추가: mapped_at_creation: false,
204추가: });
205추가: Self {
206추가: pipeline,
207추가: layout,
208추가: sampler,
209추가: params,
210추가: srgb_target: target.is_srgb(),
211추가: textures: None,
212추가: uploaded: None,
213추가: }
214추가: }
215추가:
216추가: fn upload(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: &YuvFrame) {
217추가: let key = (frame.width, frame.height, frame.nv12);
218추가: if self.textures.as_ref().map(|t| t.key) != Some(key) {
219추가: self.textures = Some(self.create_textures(device, frame));
220추가: }
221추가: let Some(tex) = &self.textures else { return };
222추가: for (texture, (data, stride, w, h)) in tex.planes.iter().zip(&frame.planes) {
223추가: queue.write_texture(
224추가: texture.as_image_copy(),
225추가: data,
226추가: wgpu::TexelCopyBufferLayout {
227추가: offset: 0,
228추가: bytes_per_row: Some(*stride as u32),
229추가: rows_per_image: Some(*h),
230추가: },
231추가: wgpu::Extent3d {
232추가: width: *w,
233추가: height: *h,
234추가: depth_or_array_layers: 1,
235추가: },
236추가: );
237추가: }
238추가: let params = Params {
239추가: nv12: frame.nv12.into(),
240추가: full_range: frame.full_range.into(),
241추가: bt709: frame.bt709.into(),
242추가: srgb_target: self.srgb_target.into(),
243추가: };
244추가: queue.write_buffer(&self.params, 0, &params.bytes());
245추가: }
246추가:
247추가: fn create_textures(&self, device: &wgpu::Device, frame: &YuvFrame) -> Textures {
248추가: let make = |w: u32, h: u32, format| {
249추가: device.create_texture(&wgpu::TextureDescriptor {
250추가: label: Some("video-plane"),
251추가: size: wgpu::Extent3d {
252추가: width: w.max(1),
253추가: height: h.max(1),
254추가: depth_or_array_layers: 1,
255추가: },
256추가: mip_level_count: 1,
257추가: sample_count: 1,
258추가: dimension: wgpu::TextureDimension::D2,
259추가: format,
260추가: usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
261추가: view_formats: &[],
262추가: })
263추가: };
264추가: let (cw, ch) = (frame.width.div_ceil(2), frame.height.div_ceil(2));
265추가: let mut planes = vec![make(
266추가: frame.width,
267추가: frame.height,
268추가: wgpu::TextureFormat::R8Unorm,
269추가: )];
270추가: if frame.nv12 {
271추가: planes.push(make(cw, ch, wgpu::TextureFormat::Rg8Unorm));
272추가: // V 자리는 쓰지 않지만 바인딩을 채우기 위해 1x1 텍스처를 둔다.
273추가: planes.push(make(1, 1, wgpu::TextureFormat::R8Unorm));
274추가: } else {
275추가: planes.push(make(cw, ch, wgpu::TextureFormat::R8Unorm));
276추가: planes.push(make(cw, ch, wgpu::TextureFormat::R8Unorm));
277추가: }
278추가: let views: Vec<_> = planes
279추가: .iter()
280추가: .map(|t| t.create_view(&Default::default()))
281추가: .collect();
282추가: let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
283추가: label: Some("video-yuv"),
284추가: layout: &self.layout,
285추가: entries: &[
286추가: wgpu::BindGroupEntry {
287추가: binding: 0,
288추가: resource: wgpu::BindingResource::Sampler(&self.sampler),
289추가: },
290추가: wgpu::BindGroupEntry {
291추가: binding: 1,
292추가: resource: wgpu::BindingResource::TextureView(&views[0]),
293추가: },
294추가: wgpu::BindGroupEntry {
295추가: binding: 2,
296추가: resource: wgpu::BindingResource::TextureView(&views[1]),
297추가: },
298추가: wgpu::BindGroupEntry {
299추가: binding: 3,
300추가: resource: wgpu::BindingResource::TextureView(&views[2]),
301추가: },
302추가: wgpu::BindGroupEntry {
303추가: binding: 4,
304추가: resource: self.params.as_entire_binding(),
305추가: },
306추가: ],
307추가: });
308추가: Textures {
309추가: key: (frame.width, frame.height, frame.nv12),
310추가: planes,
311추가: bind_group,
312추가: }
313추가: }
314추가: }
315추가:
316추가: /// 한 번의 그리기 요청. 아직 올리지 않은 번호의 프레임이면 텍스처에 쓴 뒤 그린다.
317추가: ///
318추가: /// egui는 한 프레임에 여러 패스를 돌리고 그중 하나만 그릴 수 있으므로, "새 프레임은 한 번만
319추가: /// 넘긴다" 대신 항상 최신 프레임과 번호를 넘기고 GPU 쪽에서 중복 업로드를 거른다.
320추가: pub struct VideoCallback {
321추가: pub frame: Arc<YuvFrame>,
322추가: pub seq: u64,
323추가: }
324추가:
325추가: impl CallbackTrait for VideoCallback {
326추가: fn prepare(
327추가: &self,
328추가: device: &wgpu::Device,
329추가: queue: &wgpu::Queue,
330추가: _screen: &ScreenDescriptor,
331추가: _encoder: &mut wgpu::CommandEncoder,
332추가: resources: &mut CallbackResources,
333추가: ) -> Vec<wgpu::CommandBuffer> {
334추가: if let Some(pipeline) = resources.get_mut::<VideoPipeline>()
335추가: && pipeline.uploaded != Some(self.seq)
336추가: {
337추가: pipeline.upload(device, queue, &self.frame);
338추가: pipeline.uploaded = Some(self.seq);
339추가: }
340추가: Vec::new()
341추가: }
342추가:
343추가: fn paint(
344추가: &self,
345추가: _info: egui::PaintCallbackInfo,
346추가: render_pass: &mut wgpu::RenderPass<'static>,
347추가: resources: &CallbackResources,
348추가: ) {
349추가: let Some(pipeline) = resources.get::<VideoPipeline>() else {
350추가: return;
351추가: };
352추가: let Some(tex) = &pipeline.textures else {
353추가: return;
354추가: };
355추가: render_pass.set_pipeline(&pipeline.pipeline);
356추가: render_pass.set_bind_group(0, &tex.bind_group, &[]);
357추가: render_pass.draw(0..3, 0..1);
358추가: }
359추가: }
수정src/ui/view.rs+48-1
@@ -13,6 +13,7 @@ use super::conn::ConnEvent;
1313use super::icons::{self, Icon};
1414use super::layout::{self, DEFAULT_VIEWPORT};
1515use super::recent::{RecentTargets, display_target, parse_target};
16추가: use super::video_render::{VideoCallback, YuvFrame};
1617
1718const FRAME_COLOR: Color32 = Color32::BLACK;
1819const SETTINGS_BG: Color32 = Color32::from_rgb(0x14, 0x14, 0x14);
@@ -93,6 +94,9 @@ pub struct View {
9394 focus_input: bool,
9495 recent: RecentTargets,
9596 settings: StreamSettings,
97추가: /// 최신 영상 프레임과 번호. 있으면 휴대폰 화면 영역에 영상을 그린다.
98추가: video_frame: Option<(u64, std::sync::Arc<YuvFrame>)>,
99추가: video_seq: u64,
96100}
97101
98102impl View {
@@ -106,6 +110,16 @@ impl View {
106110 focus_input: true,
107111 recent: RecentTargets::load(),
108112 settings: StreamSettings::default(),
113추가: video_frame: None,
114추가: video_seq: 0,
115추가: }
116추가: }
117추가:
118추가: /// 디코더가 만든 최신 프레임. 다음 그리기에서 GPU로 올린다.
119추가: pub fn set_video_frame(&mut self, frame: std::sync::Arc<YuvFrame>) {
120추가: if matches!(self.connection, Connection::Connected { .. }) {
121추가: self.video_seq += 1;
122추가: self.video_frame = Some((self.video_seq, frame));
109123 }
110124 }
111125
@@ -157,6 +171,7 @@ impl View {
157171 _ => None,
158172 };
159173 self.connection = Connection::Disconnected;
174추가: self.video_frame = None;
160175 self.input_error = Some(reason);
161176 self.focus_input = true;
162177 }
@@ -201,7 +216,12 @@ impl View {
201216 grant,
202217 video,
203218 frames,
204삭제: } => connected_screen(ui, layout.viewport, target, grant, video.as_ref(), frames),
219추가: } => match self.video_frame.clone() {
220추가: Some((seq, frame)) => draw_video(ui, layout.viewport, seq, frame),
221추가: None => {
222추가: connected_screen(ui, layout.viewport, target, grant, video.as_ref(), frames)
223추가: }
224추가: },
205225 }
206226 }
207227
@@ -397,8 +417,15 @@ impl View {
397417 }
398418 }
399419
420추가: /// IP 입력창에 주소를 넣고 Enter를 누른 것과 같다. 시작 인자 연결에 쓴다.
421추가: pub fn request_connect(&mut self, input: &str, actions: &mut Actions) {
422추가: self.ip_input = input.to_owned();
423추가: self.try_connect(input, actions);
424추가: }
425추가:
400426 /// 사용자가 끊었을 때 IP 입력 화면으로 돌아간다.
401427 pub fn reset_to_disconnected(&mut self) {
428추가: self.video_frame = None;
402429 self.connection = Connection::Disconnected;
403430 self.focus_input = true;
404431 }
@@ -494,6 +521,26 @@ fn connected_screen(
494521 );
495522}
496523
524추가: /// 영상을 휴대폰 화면 영역에 종횡비를 유지해 맞춰 그린다.
525추가: fn draw_video(ui: &mut Ui, viewport: Rect, seq: u64, frame: std::sync::Arc<YuvFrame>) {
526추가: let rect = fit_rect(viewport, frame.width as f32 / frame.height.max(1) as f32);
527추가: ui.painter().add(egui_wgpu::Callback::new_paint_callback(
528추가: rect,
529추가: VideoCallback { frame, seq },
530추가: ));
531추가: }
532추가:
533추가: /// `outer` 안에 종횡비 `aspect`(너비/높이)를 유지하는 가장 큰 사각형을 가운데 정렬로 구한다.
534추가: fn fit_rect(outer: Rect, aspect: f32) -> Rect {
535추가: let outer_aspect = outer.width() / outer.height();
536추가: let size = if aspect > outer_aspect {
537추가: vec2(outer.width(), outer.width() / aspect)
538추가: } else {
539추가: vec2(outer.height() * aspect, outer.height())
540추가: };
541추가: Rect::from_center_size(outer.center(), size)
542추가: }
543추가:
497544fn codec_name(codec: VideoCodec) -> &'static str {
498545 match codec {
499546 VideoCodec::H264 => "H.264",
추가src/video/decoder.rs+782-0
@@ -0,0 +1,782 @@
1추가: //! FFmpeg 기반 저지연 비디오 디코더.
2추가: //!
3추가: //! - 비디오 패킷 헤더만 보고 동작한다. CONFIG 패킷을 기억해 두었다가 키프레임마다 앞에 붙인다.
4추가: //! - `config_gen`이 바뀐 CONFIG가 오면 코덱 컨텍스트를 새로 만든다(해상도 변경 대응).
5추가: //! - 재정렬 지연이 없도록 `AV_CODEC_FLAG_LOW_DELAY`를 켜고 프레임 스레딩은 쓰지 않는다.
6추가: //! - 하드웨어(CUDA → VA-API) 디코딩이 실패하면 소프트웨어로 한 번 전환한다.
7추가:
8추가: use std::error::Error;
9추가: use std::ffi::CString;
10추가: use std::fmt;
11추가: use std::ptr;
12추가:
13추가: use ff::codec::{self, threading};
14추가: use ff::color;
15추가: use ff::format::Pixel;
16추가: use ff::software::scaling;
17추가: use ff::util::frame::video::Video as Frame;
18추가: use ffmpeg_next as ff;
19추가: use ffmpeg_sys_next as sys;
20추가: use log::{debug, info, warn};
21추가:
22추가: use crate::protocol::{VideoCodec, VideoPacketHeader};
23추가:
24추가: /// 렌더러가 처리해야 하는 평면 배치.
25추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
26추가: pub enum PlaneLayout {
27추가: /// Y, U, V 3평면. 텍셀당 1바이트, 색차 평면은 가로·세로 1/2(올림).
28추가: I420,
29추가: /// Y + 인터리브 UV 2평면. UV 평면은 텍셀당 2바이트(U, V 순), 가로·세로 1/2(올림).
30추가: Nv12,
31추가: }
32추가:
33추가: impl PlaneLayout {
34추가: pub fn plane_count(self) -> usize {
35추가: match self {
36추가: Self::I420 => 3,
37추가: Self::Nv12 => 2,
38추가: }
39추가: }
40추가:
41추가: /// `plane`번 평면의 텍셀당 바이트 수.
42추가: pub fn bytes_per_texel(self, plane: usize) -> usize {
43추가: match (self, plane) {
44추가: (Self::Nv12, 1) => 2,
45추가: _ => 1,
46추가: }
47추가: }
48추가: }
49추가:
50추가: /// 디코딩된 한 평면. 행 사이 패딩 없이 담는다(`stride == width * 텍셀당 바이트`).
51추가: #[derive(Debug, Clone, PartialEq, Eq)]
52추가: pub struct Plane {
53추가: pub data: Vec<u8>,
54추가: /// 행 간격(바이트).
55추가: pub stride: usize,
56추가: /// 텍셀 단위 너비.
57추가: pub width: u32,
58추가: /// 행 수.
59추가: pub height: u32,
60추가: }
61추가:
62추가: /// YUV→RGB 변환 행렬.
63추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
64추가: pub enum ColorMatrix {
65추가: Bt601,
66추가: Bt709,
67추가: }
68추가:
69추가: /// 프레임 색 정보. 스트림에 명시되지 않으면 BT.709 제한 범위.
70추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
71추가: pub struct ColorInfo {
72추가: pub matrix: ColorMatrix,
73추가: /// true면 0~255 전체 범위, false면 16~235(색차 16~240) 제한 범위.
74추가: pub full_range: bool,
75추가: }
76추가:
77추가: impl Default for ColorInfo {
78추가: fn default() -> Self {
79추가: Self {
80추가: matrix: ColorMatrix::Bt709,
81추가: full_range: false,
82추가: }
83추가: }
84추가: }
85추가:
86추가: /// 렌더러에 넘길 시스템 메모리 프레임.
87추가: #[derive(Debug, Clone)]
88추가: pub struct DecodedFrame {
89추가: pub width: u32,
90추가: pub height: u32,
91추가: pub layout: PlaneLayout,
92추가: /// `layout.plane_count()`개.
93추가: pub planes: Vec<Plane>,
94추가: pub color: ColorInfo,
95추가: pub pts_us: u64,
96추가: pub config_gen: u8,
97추가: }
98추가:
99추가: /// 실제 디코딩을 수행하는 백엔드.
100추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
101추가: pub enum Backend {
102추가: /// NVDEC (CUDA hwaccel).
103추가: Cuda,
104추가: Vaapi,
105추가: Software,
106추가: }
107추가:
108추가: impl Backend {
109추가: fn hw(self) -> Option<(sys::AVHWDeviceType, GetFormatFn)> {
110추가: match self {
111추가: Self::Cuda => Some((sys::AVHWDeviceType::AV_HWDEVICE_TYPE_CUDA, get_format_cuda)),
112추가: Self::Vaapi => Some((
113추가: sys::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
114추가: get_format_vaapi,
115추가: )),
116추가: Self::Software => None,
117추가: }
118추가: }
119추가: }
120추가:
121추가: impl fmt::Display for Backend {
122추가: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123추가: f.write_str(match self {
124추가: Self::Cuda => "CUDA(NVDEC)",
125추가: Self::Vaapi => "VA-API",
126추가: Self::Software => "소프트웨어",
127추가: })
128추가: }
129추가: }
130추가:
131추가: #[derive(Debug, Clone, PartialEq, Eq)]
132추가: pub enum DecodeError {
133추가: /// 디코더를 만들 수 없음. 복구 불가.
134추가: Init(String),
135추가: /// 이 패킷을 디코딩하지 못함. 키프레임을 요청하고 계속 넣으면 된다.
136추가: Corrupt(String),
137추가: /// 백엔드 전환 등으로 참조 프레임을 잃음. 키프레임 전까지 일반 프레임은 버린다.
138추가: NeedKeyframe,
139추가: }
140추가:
141추가: impl DecodeError {
142추가: /// 호출자가 기기에 키프레임을 요청해야 하는 오류인지.
143추가: pub fn needs_keyframe(&self) -> bool {
144추가: matches!(self, Self::Corrupt(_) | Self::NeedKeyframe)
145추가: }
146추가: }
147추가:
148추가: impl fmt::Display for DecodeError {
149추가: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150추가: match self {
151추가: Self::Init(m) => write!(f, "디코더 초기화 실패: {m}"),
152추가: Self::Corrupt(m) => write!(f, "패킷 디코딩 실패: {m}"),
153추가: Self::NeedKeyframe => f.write_str("키프레임 필요"),
154추가: }
155추가: }
156추가: }
157추가:
158추가: impl Error for DecodeError {}
159추가:
160추가: /// 저지연 디코더. 한 비디오 채널에 하나.
161추가: pub struct Decoder {
162추가: codec: VideoCodec,
163추가: /// None이면 소프트웨어 디코딩.
164추가: device: Option<HwDevice>,
165추가: dec: ff::decoder::Video,
166추가: /// 현재 컨텍스트에 패킷을 넣은 적이 있는지.
167추가: fed: bool,
168추가: /// 현재 컨텍스트가 프레임을 한 장이라도 냈는지. hw 실패 판단에 쓴다.
169추가: produced: bool,
170추가: cur_gen: Option<u8>,
171추가: /// 현재 세대의 코덱 설정(Annex-B 파라미터 셋).
172추가: config: Option<Vec<u8>>,
173추가: have_keyframe: bool,
174추가: frame: Frame,
175추가: /// hw 프레임을 시스템 메모리로 옮길 버퍼.
176추가: sw_frame: Frame,
177추가: scaler: Option<Scaler>,
178추가: }
179추가:
180추가: impl Decoder {
181추가: /// `prefer_hw`면 CUDA → VA-API → 소프트웨어 순으로 시도한다.
182추가: pub fn new(codec: VideoCodec, prefer_hw: bool) -> Result<Self, DecodeError> {
183추가: if prefer_hw {
184추가: Self::with_backends(codec, &[Backend::Cuda, Backend::Vaapi, Backend::Software])
185추가: } else {
186추가: Self::with_backends(codec, &[Backend::Software])
187추가: }
188추가: }
189추가:
190추가: /// `order` 순서대로 처음 열리는 백엔드를 쓴다.
191추가: pub fn with_backends(codec: VideoCodec, order: &[Backend]) -> Result<Self, DecodeError> {
192추가: let mut last = String::from("백엔드 목록이 비어 있음");
193추가: for &backend in order {
194추가: match Self::open_backend(codec, backend) {
195추가: Ok(d) => {
196추가: info!("비디오 디코더: {codec:?} / {backend}");
197추가: return Ok(d);
198추가: }
199추가: Err(e) => {
200추가: info!("{backend} 디코더 사용 불가({codec:?}): {e}");
201추가: last = format!("{backend}: {e}");
202추가: }
203추가: }
204추가: }
205추가: Err(DecodeError::Init(last))
206추가: }
207추가:
208추가: fn open_backend(codec: VideoCodec, backend: Backend) -> Result<Self, String> {
209추가: let device = match backend.hw() {
210추가: None => None,
211추가: Some(_) => Some(HwDevice::create(codec, backend)?),
212추가: };
213추가: let dec = open_context(codec, device.as_ref())?;
214추가: Ok(Self {
215추가: codec,
216추가: device,
217추가: dec,
218추가: fed: false,
219추가: produced: false,
220추가: cur_gen: None,
221추가: config: None,
222추가: have_keyframe: false,
223추가: frame: Frame::empty(),
224추가: sw_frame: Frame::empty(),
225추가: scaler: None,
226추가: })
227추가: }
228추가:
229추가: pub fn backend(&self) -> Backend {
230추가: self.device
231추가: .as_ref()
232추가: .map_or(Backend::Software, |d| d.backend)
233추가: }
234추가:
235추가: pub fn codec(&self) -> VideoCodec {
236추가: self.codec
237추가: }
238추가:
239추가: /// 패킷 하나를 넣고 지금 나온 프레임(0..n장)을 돌려준다.
240추가: ///
241추가: /// 설정을 받지 못한 세대의 패킷, 키프레임 전의 일반 프레임은 조용히 버린다.
242추가: pub fn decode(
243추가: &mut self,
244추가: header: &VideoPacketHeader,
245추가: data: &[u8],
246추가: ) -> Result<Vec<DecodedFrame>, DecodeError> {
247추가: if header.is_config {
248추가: return self.handle_config(header.config_gen, data);
249추가: }
250추가: if self.cur_gen != Some(header.config_gen) || self.config.is_none() {
251추가: debug!("설정 전 세대 {} 패킷 버림", header.config_gen);
252추가: return Ok(Vec::new());
253추가: }
254추가: if data.is_empty() || (!header.is_keyframe && !self.have_keyframe) {
255추가: debug!("키프레임 전 패킷 버림 (pts {})", header.pts_us);
256추가: return Ok(Vec::new());
257추가: }
258추가: let packet = self.build_packet(header, data)?;
259추가: if header.is_keyframe {
260추가: self.have_keyframe = true;
261추가: }
262추가: self.feed(&packet, header.is_keyframe)
263추가: }
264추가:
265추가: fn handle_config(
266추가: &mut self,
267추가: new_gen: u8,
268추가: data: &[u8],
269추가: ) -> Result<Vec<DecodedFrame>, DecodeError> {
270추가: let config = normalize_config(self.codec, data);
271추가: if config.is_empty() {
272추가: warn!("빈 CONFIG 패킷 무시 (세대 {new_gen})");
273추가: return Ok(Vec::new());
274추가: }
275추가: let same_gen = self.cur_gen == Some(new_gen);
276추가: if same_gen && self.config.as_deref() == Some(config) {
277추가: return Ok(Vec::new());
278추가: }
279추가: let mut out = Vec::new();
280추가: if self.fed {
281추가: // 이전 세대 잔여 프레임을 비우고 컨텍스트를 새로 만든다.
282추가: if let Err(f) = self.run(None, &mut out) {
283추가: debug!("이전 세대 비우기 실패: {}", f.message());
284추가: }
285추가: self.reopen()?;
286추가: }
287추가: if !same_gen {
288추가: info!("비디오 설정 세대 {new_gen} ({} 바이트)", config.len());
289추가: }
290추가: self.cur_gen = Some(new_gen);
291추가: self.config = Some(config.to_vec());
292추가: self.have_keyframe = false;
293추가: Ok(out)
294추가: }
295추가:
296추가: /// 키프레임이면 설정을 앞에 붙여 한 번만 복사한다.
297추가: fn build_packet(
298추가: &self,
299추가: header: &VideoPacketHeader,
300추가: data: &[u8],
301추가: ) -> Result<ff::Packet, DecodeError> {
302추가: let prefix: &[u8] = match (&self.config, header.is_keyframe) {
303추가: (Some(c), true) => c,
304추가: _ => &[],
305추가: };
306추가: let mut packet = ff::Packet::new(prefix.len() + data.len());
307추가: let buf = packet
308추가: .data_mut()
309추가: .ok_or_else(|| DecodeError::Corrupt("패킷 버퍼 할당 실패".into()))?;
310추가: buf[..prefix.len()].copy_from_slice(prefix);
311추가: buf[prefix.len()..].copy_from_slice(data);
312추가: let pts = i64::try_from(header.pts_us).unwrap_or(i64::MAX);
313추가: packet.set_pts(Some(pts));
314추가: packet.set_dts(Some(pts));
315추가: if header.is_keyframe {
316추가: packet.set_flags(codec::packet::Flags::KEY);
317추가: }
318추가: Ok(packet)
319추가: }
320추가:
321추가: fn feed(
322추가: &mut self,
323추가: packet: &ff::Packet,
324추가: is_keyframe: bool,
325추가: ) -> Result<Vec<DecodedFrame>, DecodeError> {
326추가: self.fed = true;
327추가: let mut out = Vec::new();
328추가: let fail = match self.run(Some(packet), &mut out) {
329추가: Ok(()) => return Ok(out),
330추가: Err(f) => f,
331추가: };
332추가: // 한 번도 프레임을 못 냈거나 전송 자체가 실패하면 hw가 이 스트림을 못 다루는 것으로 본다.
333추가: let hw_broken = self.device.is_some() && (matches!(fail, Fail::Hw(_)) || !self.produced);
334추가: if !hw_broken {
335추가: return Err(DecodeError::Corrupt(fail.message().to_owned()));
336추가: }
337추가: warn!(
338추가: "{} 디코딩 실패({}), 소프트웨어 디코더로 전환",
339추가: self.backend(),
340추가: fail.message()
341추가: );
342추가: self.switch_to_software()?;
343추가: if !is_keyframe {
344추가: self.have_keyframe = false;
345추가: return Err(DecodeError::NeedKeyframe);
346추가: }
347추가: // 키프레임은 설정이 붙어 있으므로 새 디코더에 그대로 다시 넣는다.
348추가: out.clear();
349추가: self.fed = true;
350추가: self.run(Some(packet), &mut out)
351추가: .map_err(|f| DecodeError::Corrupt(f.message().to_owned()))?;
352추가: Ok(out)
353추가: }
354추가:
355추가: fn reopen(&mut self) -> Result<(), DecodeError> {
356추가: match open_context(self.codec, self.device.as_ref()) {
357추가: Ok(dec) => {
358추가: self.dec = dec;
359추가: self.fed = false;
360추가: self.produced = false;
361추가: Ok(())
362추가: }
363추가: Err(e) if self.device.is_some() => {
364추가: warn!(
365추가: "{} 디코더 재생성 실패({e}), 소프트웨어로 전환",
366추가: self.backend()
367추가: );
368추가: self.switch_to_software()
369추가: }
370추가: Err(e) => Err(DecodeError::Init(e)),
371추가: }
372추가: }
373추가:
374추가: fn switch_to_software(&mut self) -> Result<(), DecodeError> {
375추가: self.dec = open_context(self.codec, None).map_err(DecodeError::Init)?;
376추가: self.device = None;
377추가: self.fed = false;
378추가: self.produced = false;
379추가: Ok(())
380추가: }
381추가:
382추가: /// 패킷(None이면 EOF)을 넣고 나온 프레임을 모두 꺼낸다.
383추가: fn run(
384추가: &mut self,
385추가: packet: Option<&ff::Packet>,
386추가: out: &mut Vec<DecodedFrame>,
387추가: ) -> Result<(), Fail> {
388추가: let send = |dec: &mut ff::decoder::Video| match packet {
389추가: Some(p) => dec.send_packet(p),
390추가: None => dec.send_eof(),
391추가: };
392추가: match send(&mut self.dec) {
393추가: Ok(()) => {}
394추가: Err(e) if is_again(&e) => {
395추가: // 출력이 쌓여 입력을 거부함: 먼저 꺼낸 뒤 다시 넣는다.
396추가: self.receive_all(out)?;
397추가: send(&mut self.dec).map_err(|e| Fail::Codec(e.to_string()))?;
398추가: }
399추가: Err(ff::Error::Eof) => {}
400추가: Err(e) => return Err(Fail::Codec(e.to_string())),
401추가: }
402추가: self.receive_all(out)
403추가: }
404추가:
405추가: fn receive_all(&mut self, out: &mut Vec<DecodedFrame>) -> Result<(), Fail> {
406추가: loop {
407추가: match self.dec.receive_frame(&mut self.frame) {
408추가: Ok(()) => {
409추가: out.push(self.convert()?);
410추가: self.produced = true;
411추가: }
412추가: Err(ff::Error::Eof) => return Ok(()),
413추가: Err(e) if is_again(&e) => return Ok(()),
414추가: Err(e) => return Err(Fail::Codec(e.to_string())),
415추가: }
416추가: }
417추가: }
418추가:
419추가: /// `self.frame`을 시스템 메모리 평면으로 복사한다.
420추가: fn convert(&mut self) -> Result<DecodedFrame, Fail> {
421추가: let frame = &self.frame;
422추가: let color = color_info(frame);
423추가: let pts_us = frame.pts().and_then(|p| u64::try_from(p).ok()).unwrap_or(0);
424추가: // SAFETY: frame은 receive_frame이 채운 유효한 AVFrame.
425추가: let is_hw = unsafe { !(*frame.as_ptr()).hw_frames_ctx.is_null() };
426추가: let src = if is_hw {
427추가: // SAFETY: 두 포인터 모두 유효한 AVFrame. sw_frame을 비운 뒤 넘기면 FFmpeg가
428추가: // 첫 지원 형식(8비트면 NV12)으로 버퍼를 할당하고 크롭된 크기를 설정한다.
429추가: let r = unsafe {
430추가: sys::av_frame_unref(self.sw_frame.as_mut_ptr());
431추가: sys::av_hwframe_transfer_data(self.sw_frame.as_mut_ptr(), frame.as_ptr(), 0)
432추가: };
433추가: if r < 0 {
434추가: return Err(Fail::Hw(format!(
435추가: "av_hwframe_transfer_data: {}",
436추가: ff::Error::from(r)
437추가: )));
438추가: }
439추가: &self.sw_frame
440추가: } else {
441추가: frame
442추가: };
443추가: let (layout, planes) = to_planes(src, &mut self.scaler).map_err(Fail::Convert)?;
444추가: Ok(DecodedFrame {
445추가: width: src.width(),
446추가: height: src.height(),
447추가: layout,
448추가: planes,
449추가: color: ColorInfo {
450추가: full_range: color.full_range || src.format() == Pixel::YUVJ420P,
451추가: ..color
452추가: },
453추가: pts_us,
454추가: config_gen: self.cur_gen.unwrap_or(0),
455추가: })
456추가: }
457추가: }
458추가:
459추가: /// 디코딩 경로 내부 실패. hw 전용 실패는 소프트웨어 전환 근거가 된다.
460추가: enum Fail {
461추가: Codec(String),
462추가: Hw(String),
463추가: Convert(String),
464추가: }
465추가:
466추가: impl Fail {
467추가: fn message(&self) -> &str {
468추가: match self {
469추가: Self::Codec(m) | Self::Hw(m) | Self::Convert(m) => m,
470추가: }
471추가: }
472추가: }
473추가:
474추가: fn is_again(e: &ff::Error) -> bool {
475추가: matches!(e, ff::Error::Other { errno } if *errno == ff::util::error::EAGAIN)
476추가: }
477추가:
478추가: type GetFormatFn =
479추가: unsafe extern "C" fn(*mut sys::AVCodecContext, *const sys::AVPixelFormat) -> sys::AVPixelFormat;
480추가:
481추가: unsafe extern "C" fn get_format_cuda(
482추가: _ctx: *mut sys::AVCodecContext,
483추가: fmts: *const sys::AVPixelFormat,
484추가: ) -> sys::AVPixelFormat {
485추가: // SAFETY: FFmpeg가 AV_PIX_FMT_NONE으로 끝나는 목록을 넘긴다.
486추가: unsafe { pick_format(fmts, sys::AVPixelFormat::AV_PIX_FMT_CUDA) }
487추가: }
488추가:
489추가: unsafe extern "C" fn get_format_vaapi(
490추가: _ctx: *mut sys::AVCodecContext,
491추가: fmts: *const sys::AVPixelFormat,
492추가: ) -> sys::AVPixelFormat {
493추가: // SAFETY: get_format_cuda와 같음.
494추가: unsafe { pick_format(fmts, sys::AVPixelFormat::AV_PIX_FMT_VAAPI) }
495추가: }
496추가:
497추가: /// 목록에 hw 형식이 없으면 NONE을 돌려 디코딩을 실패시킨다(→ 소프트웨어 전환).
498추가: ///
499추가: /// # Safety
500추가: /// `fmts`는 AV_PIX_FMT_NONE으로 끝나는 유효한 배열이어야 한다.
501추가: unsafe fn pick_format(
502추가: mut fmts: *const sys::AVPixelFormat,
503추가: want: sys::AVPixelFormat,
504추가: ) -> sys::AVPixelFormat {
505추가: use sys::AVPixelFormat::AV_PIX_FMT_NONE;
506추가: if fmts.is_null() {
507추가: return AV_PIX_FMT_NONE;
508추가: }
509추가: // SAFETY: 호출자 보장. NONE을 만나기 전까지만 읽는다.
510추가: unsafe {
511추가: while *fmts != AV_PIX_FMT_NONE {
512추가: if *fmts == want {
513추가: return want;
514추가: }
515추가: fmts = fmts.add(1);
516추가: }
517추가: }
518추가: AV_PIX_FMT_NONE
519추가: }
520추가:
521추가: /// hw 디바이스 컨텍스트 참조.
522추가: struct HwDevice {
523추가: backend: Backend,
524추가: get_format: GetFormatFn,
525추가: buf: *mut sys::AVBufferRef,
526추가: }
527추가:
528추가: // SAFETY: AVBufferRef 참조 카운트는 원자적이고 디바이스 컨텍스트는 스레드 간 이동이 허용된다.
529추가: unsafe impl Send for HwDevice {}
530추가:
531추가: impl HwDevice {
532추가: fn create(codec: VideoCodec, backend: Backend) -> Result<Self, String> {
533추가: let (ty, get_format) = backend.hw().ok_or("hw 백엔드가 아님")?;
534추가: let dec = find_decoder(codec, true)?;
535추가: if !supports_device(&dec, ty) {
536추가: return Err(format!(
537추가: "{} 디코더가 이 hw 가속을 지원하지 않음",
538추가: dec.name()
539추가: ));
540추가: }
541추가: // VA-API 기본 장치는 첫 렌더 노드라서 드라이버가 없는 GPU(예: iGPU)를 고를 수 있다.
542추가: // 실패하면 렌더 노드를 차례로 시도한다.
543추가: let mut candidates: Vec<Option<CString>> = vec![None];
544추가: if backend == Backend::Vaapi {
545추가: candidates.extend(render_nodes().into_iter().map(Some));
546추가: }
547추가: let mut last = String::new();
548추가: let mut found = None;
549추가: for dev in &candidates {
550추가: let mut buf = ptr::null_mut();
551추가: let dev_ptr = dev.as_ref().map_or(ptr::null(), |d| d.as_ptr());
552추가: // SAFETY: buf는 출력 인자, dev_ptr은 NULL 또는 살아 있는 C 문자열, opts는 NULL 허용.
553추가: let r =
554추가: unsafe { sys::av_hwdevice_ctx_create(&mut buf, ty, dev_ptr, ptr::null_mut(), 0) };
555추가: if r >= 0 && !buf.is_null() {
556추가: if let Some(d) = dev {
557추가: info!("{backend} 장치: {}", d.to_string_lossy());
558추가: }
559추가: found = Some(buf);
560추가: break;
561추가: }
562추가: last = format!("av_hwdevice_ctx_create: {}", ff::Error::from(r));
563추가: }
564추가: let buf = found.ok_or(last)?;
565추가: Ok(Self {
566추가: backend,
567추가: get_format,
568추가: buf,
569추가: })
570추가: }
571추가: }
572추가:
573추가: /// `/dev/dri/renderD*` 경로(이름순).
574추가: fn render_nodes() -> Vec<CString> {
575추가: let Ok(dir) = std::fs::read_dir("/dev/dri") else {
576추가: return Vec::new();
577추가: };
578추가: let mut nodes: Vec<String> = dir
579추가: .filter_map(|e| e.ok())
580추가: .map(|e| e.file_name().to_string_lossy().into_owned())
581추가: .filter(|n| n.starts_with("renderD"))
582추가: .collect();
583추가: nodes.sort();
584추가: nodes
585추가: .into_iter()
586추가: .filter_map(|n| CString::new(format!("/dev/dri/{n}")).ok())
587추가: .collect()
588추가: }
589추가:
590추가: impl Drop for HwDevice {
591추가: fn drop(&mut self) {
592추가: // SAFETY: create에서 얻은 참조를 한 번만 해제한다.
593추가: unsafe { sys::av_buffer_unref(&mut self.buf) };
594추가: }
595추가: }
596추가:
597추가: fn supports_device(dec: &ff::Codec, ty: sys::AVHWDeviceType) -> bool {
598추가: let method = sys::AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX as i32;
599추가: for i in 0.. {
600추가: // SAFETY: 유효한 AVCodec 포인터. 범위를 넘으면 NULL을 돌려준다.
601추가: let cfg = unsafe { sys::avcodec_get_hw_config(dec.as_ptr(), i) };
602추가: if cfg.is_null() {
603추가: return false;
604추가: }
605추가: // SAFETY: NULL이 아닌 정적 설정 구조체.
606추가: let cfg = unsafe { &*cfg };
607추가: if cfg.methods & method != 0 && cfg.device_type == ty {
608추가: return true;
609추가: }
610추가: }
611추가: false
612추가: }
613추가:
614추가: /// 내장 디코더를 이름으로 고른다(cuvid 등 래퍼 디코더를 피하기 위해).
615추가: fn find_decoder(codec: VideoCodec, hw: bool) -> Result<ff::Codec, String> {
616추가: let (names, id): (&[&str], _) = match (codec, hw) {
617추가: (VideoCodec::H264, _) => (&["h264"], codec::Id::H264),
618추가: (VideoCodec::H265, _) => (&["hevc"], codec::Id::HEVC),
619추가: // AV1 hw 가속은 내장 av1 디코더에서만, 소프트웨어는 dav1d가 빠르다.
620추가: (VideoCodec::Av1, true) => (&["av1"], codec::Id::AV1),
621추가: (VideoCodec::Av1, false) => (&["libdav1d", "libaom-av1"], codec::Id::AV1),
622추가: };
623추가: names
624추가: .iter()
625추가: .find_map(|n| ff::decoder::find_by_name(n))
626추가: .or_else(|| if hw { None } else { ff::decoder::find(id) })
627추가: .ok_or_else(|| format!("{codec:?} 디코더를 찾을 수 없음"))
628추가: }
629추가:
630추가: fn open_context(
631추가: codec: VideoCodec,
632추가: device: Option<&HwDevice>,
633추가: ) -> Result<ff::decoder::Video, String> {
634추가: let dec_codec = find_decoder(codec, device.is_some())?;
635추가: let mut ctx = codec::Context::new_with_codec(dec_codec);
636추가: ctx.set_flags(codec::Flags::LOW_DELAY);
637추가: // 프레임 스레딩은 스레드 수만큼 출력이 늦어지므로 슬라이스 스레딩만 쓴다.
638추가: let mut threads = threading::Config::kind(threading::Type::Slice);
639추가: threads.count = if device.is_some() { 1 } else { 0 };
640추가: ctx.set_threading(threads);
641추가: if let Some(dev) = device {
642추가: // SAFETY: 열기 전 컨텍스트 필드 설정. hw_device_ctx에는 새 참조를 넘기며
643추가: // avcodec_free_context가 해제한다.
644추가: unsafe {
645추가: let p = ctx.as_mut_ptr();
646추가: let r = sys::av_buffer_ref(dev.buf);
647추가: if r.is_null() {
648추가: return Err("av_buffer_ref 실패".into());
649추가: }
650추가: (*p).hw_device_ctx = r;
651추가: (*p).get_format = Some(dev.get_format);
652추가: }
653추가: }
654추가: let mut d = ctx.decoder();
655추가: d.set_packet_time_base((1, 1_000_000));
656추가: d.open_as(dec_codec)
657추가: .and_then(|o| o.video())
658추가: .map_err(|e| format!("{} 열기 실패: {e}", dec_codec.name()))
659추가: }
660추가:
661추가: /// MediaCodec AV1 CSD는 av1C 박스(4바이트 헤더 + OBU)일 수 있으므로 OBU만 남긴다.
662추가: fn normalize_config(codec: VideoCodec, data: &[u8]) -> &[u8] {
663추가: match (codec, data) {
664추가: (VideoCodec::Av1, [0x81, _, _, _, rest @ ..]) => rest,
665추가: _ => data,
666추가: }
667추가: }
668추가:
669추가: fn color_info(frame: &Frame) -> ColorInfo {
670추가: let matrix = match frame.color_space() {
671추가: color::Space::BT470BG | color::Space::SMPTE170M | color::Space::FCC => ColorMatrix::Bt601,
672추가: _ => ColorMatrix::Bt709,
673추가: };
674추가: ColorInfo {
675추가: matrix,
676추가: full_range: frame.color_range() == color::Range::JPEG,
677추가: }
678추가: }
679추가:
680추가: /// SwsContext 래퍼. I420/NV12가 아닌 출력(10비트 등)을 I420으로 바꾼다.
681추가: struct Scaler {
682추가: key: (Pixel, u32, u32),
683추가: ctx: scaling::Context,
684추가: out: Frame,
685추가: }
686추가:
687추가: // SAFETY: SwsContext는 공유하지 않고 소유 스레드 하나에서만 쓰므로 이동은 안전하다.
688추가: unsafe impl Send for Scaler {}
689추가:
690추가: fn to_planes(
691추가: src: &Frame,
692추가: scaler: &mut Option<Scaler>,
693추가: ) -> Result<(PlaneLayout, Vec<Plane>), String> {
694추가: let (w, h) = (src.width(), src.height());
695추가: if w == 0 || h == 0 {
696추가: return Err("크기가 0인 프레임".into());
697추가: }
698추가: let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
699추가: match src.format() {
700추가: Pixel::YUV420P | Pixel::YUVJ420P => Ok((
701추가: PlaneLayout::I420,
702추가: vec![
703추가: copy_plane(src, 0, w, h, 1)?,
704추가: copy_plane(src, 1, cw, ch, 1)?,
705추가: copy_plane(src, 2, cw, ch, 1)?,
706추가: ],
707추가: )),
708추가: Pixel::NV12 => Ok((
709추가: PlaneLayout::Nv12,
710추가: vec![copy_plane(src, 0, w, h, 1)?, copy_plane(src, 1, cw, ch, 2)?],
711추가: )),
712추가: other => {
713추가: let key = (other, w, h);
714추가: if scaler.as_ref().is_none_or(|s| s.key != key) {
715추가: debug!("{other:?} 출력을 I420으로 변환");
716추가: let ctx = scaling::Context::get(
717추가: other,
718추가: w,
719추가: h,
720추가: Pixel::YUV420P,
721추가: w,
722추가: h,
723추가: scaling::Flags::BILINEAR,
724추가: )
725추가: .map_err(|e| format!("swscale 생성 실패({other:?}): {e}"))?;
726추가: *scaler = Some(Scaler {
727추가: key,
728추가: ctx,
729추가: out: Frame::empty(),
730추가: });
731추가: }
732추가: let s = scaler.as_mut().ok_or("swscale 없음")?;
733추가: s.ctx
734추가: .run(src, &mut s.out)
735추가: .map_err(|e| format!("swscale 실패: {e}"))?;
736추가: Ok((
737추가: PlaneLayout::I420,
738추가: vec![
739추가: copy_plane(&s.out, 0, w, h, 1)?,
740추가: copy_plane(&s.out, 1, cw, ch, 1)?,
741추가: copy_plane(&s.out, 2, cw, ch, 1)?,
742추가: ],
743추가: ))
744추가: }
745추가: }
746추가: }
747추가:
748추가: /// linesize 패딩을 제거해 빽빽한 평면으로 복사한다.
749추가: fn copy_plane(
750추가: src: &Frame,
751추가: index: usize,
752추가: width: u32,
753추가: height: u32,
754추가: bpt: usize,
755추가: ) -> Result<Plane, String> {
756추가: if index >= src.planes() {
757추가: return Err(format!("평면 {index} 없음 ({:?})", src.format()));
758추가: }
759추가: let row = width as usize * bpt;
760추가: let rows = height as usize;
761추가: let stride = src.stride(index);
762추가: let data = src.data(index);
763추가: if stride < row || data.len() < stride * (rows - 1) + row {
764추가: return Err(format!(
765추가: "평면 {index} 크기 불일치 (stride {stride}, 행 {row}B x {rows})"
766추가: ));
767추가: }
768추가: let mut buf = Vec::with_capacity(row * rows);
769추가: if stride == row {
770추가: buf.extend_from_slice(&data[..row * rows]);
771추가: } else {
772추가: for line in data.chunks(stride).take(rows) {
773추가: buf.extend_from_slice(&line[..row]);
774추가: }
775추가: }
776추가: Ok(Plane {
777추가: data: buf,
778추가: stride: row,
779추가: width,
780추가: height,
781추가: })
782추가: }
추가src/video/mod.rs+10-0
@@ -0,0 +1,10 @@
1추가: //! 비디오 수신 처리.
2추가: //!
3추가: //! 기기가 보낸 Annex-B 접근 단위(H.264/H.265, 이후 AV1)를 FFmpeg로 디코딩해
4추가: //! 렌더러가 올릴 수 있는 YUV 평면으로 돌려준다.
5추가:
6추가: mod decoder;
7추가:
8추가: pub use decoder::{
9추가: Backend, ColorInfo, ColorMatrix, DecodeError, DecodedFrame, Decoder, Plane, PlaneLayout,
10추가: };
추가tests/video_decode.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기