leejunyoung5819wayland-android-remote

공개

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

270줄12 KB
1package com.androidremote.daemon
2
3import android.graphics.Rect
4import android.hardware.display.DisplayManager
5import android.hardware.display.VirtualDisplay
6import android.media.MediaCodec
7import android.media.MediaCodecInfo
8import android.media.MediaCodecList
9import android.media.MediaFormat
10import android.os.Bundle
11import android.os.IBinder
12import android.view.Surface
13import java.io.IOException
14import java.io.OutputStream
15import java.nio.ByteBuffer
16import java.util.concurrent.ArrayBlockingQueue
17import java.util.concurrent.TimeUnit
18
19/** 하드웨어 영상 인코더 목록 (기획서 7.6 "캡처와 인코딩"). */
20object 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 */
57class VideoStreamer(
58 private val output: OutputStream,
59 private val peer: String,
60 /** 기기 화면 방향이 바뀌었을 때. 호출 측이 새 설정으로 [reconfigure]한다. */
61 private val onDisplayRotated: () -> Unit,
62) {
63 private class Packet(val ptsUs: Long, val flags: Int, val gen: Int, val data: ByteArray)
64
65 private val queue = ArrayBlockingQueue<Packet>(QUEUE_LIMIT)
66 @Volatile private var running = true
67 @Volatile private var pending: Messages.VideoConfig? = null
68 @Volatile private var currentCodec: MediaCodec? = null
69 @Volatile private var waitingKeyframe = false
70 private var encoderThread: Thread? = null
71 private var writerThread: Thread? = null
72
73 fun start(config: Messages.VideoConfig) {
74 pending = config
75 writerThread = Thread(::writeLoop, "video-writer").also { it.start() }
76 encoderThread = Thread(::encodeLoop, "video-encoder").also { it.start() }
77 }
78
79 /** 해상도·비트레이트·코덱이 바뀌면 인코더를 다시 만든다. */
80 fun reconfigure(config: Messages.VideoConfig) {
81 pending = config
82 }
83
84 fun requestKeyframe() {
85 val codec = currentCodec ?: return
86 try {
87 codec.setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) })
88 } catch (e: IllegalStateException) {
89 // 인코더가 막 교체되는 중이면 무시한다. 새 인코더는 키프레임으로 시작한다.
90 }
91 }
92
93 fun stop() {
94 running = false
95 encoderThread?.interrupt()
96 writerThread?.interrupt()
97 }
98
99 private fun encodeLoop() {
100 try {
101 while (running) {
102 val config = pending ?: break
103 pending = null
104 runEncoder(config)
105 }
106 } catch (e: Exception) {
107 Log.w("$peer: 인코더 오류 $e")
108 } finally {
109 running = false
110 writerThread?.interrupt()
111 }
112 }
113
114 private fun runEncoder(cfg: Messages.VideoConfig) {
115 val name = Encoders.hardware[cfg.codec] ?: throw IOException("하드웨어 인코더 없음: codec=${cfg.codec}")
116 val codec = MediaCodec.createByCodecName(name)
117 val format = MediaFormat.createVideoFormat(Encoders.mimeOf(cfg.codec), cfg.width, cfg.height).apply {
118 setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
119 setInteger(MediaFormat.KEY_BIT_RATE, cfg.bitrate.toInt())
120 setInteger(MediaFormat.KEY_FRAME_RATE, cfg.fps)
121 setFloat(MediaFormat.KEY_MAX_FPS_TO_ENCODER, cfg.fps.toFloat())
122 setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, KEYFRAME_INTERVAL_S)
123 // 화면 변화가 없어도 마지막 프레임을 다시 보내 정지 화면처럼 보이지 않게 한다.
124 setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_AFTER_US)
125 setInteger(MediaFormat.KEY_PRIORITY, 0)
126 setInteger(MediaFormat.KEY_MAX_B_FRAMES, 0)
127 setInteger(MediaFormat.KEY_LATENCY, 1)
128 val caps = codec.codecInfo.getCapabilitiesForType(Encoders.mimeOf(cfg.codec))
129 if (caps.encoderCapabilities.isBitrateModeSupported(
130 MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)) {
131 setInteger(MediaFormat.KEY_BITRATE_MODE, MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR)
132 }
133 }
134 codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
135 val surface = codec.createInputSurface()
136 val display = DisplayCapture.mirror("android-remote", cfg.width, cfg.height, cfg.displayWidth, cfg.displayHeight, surface)
137 codec.start()
138 currentCodec = codec
139 waitingKeyframe = false
140 Log.i("$peer: 인코딩 시작 $name ${cfg.width}x${cfg.height} ${cfg.fps}fps ${cfg.bitrate / 1000}kbps gen=${cfg.configGen} (${display.method})")
141
142 val info = MediaCodec.BufferInfo()
143 var lastRotationCheck = 0L
144 var rotationReported = false
145 try {
146 while (running && pending == null) {
147 val now = android.os.SystemClock.uptimeMillis()
148 if (!rotationReported && now - lastRotationCheck >= ROTATION_CHECK_MS) {
149 lastRotationCheck = now
150 val size = SystemAccess.displaySize()
151 if (size != null && (size.first > size.second) != (cfg.displayWidth > cfg.displayHeight)) {
152 rotationReported = true
153 onDisplayRotated()
154 }
155 }
156 val index = codec.dequeueOutputBuffer(info, DEQUEUE_TIMEOUT_US)
157 if (index < 0) continue
158 val buf: ByteBuffer = codec.getOutputBuffer(index) ?: run {
159 codec.releaseOutputBuffer(index, false)
160 continue
161 }
162 if (info.size > 0) {
163 val data = ByteArray(info.size)
164 buf.position(info.offset)
165 buf.get(data, 0, info.size)
166 val isConfig = info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0
167 val isKey = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
168 var flags = 0
169 if (isConfig) flags = flags or FLAG_CONFIG
170 if (isKey) flags = flags or FLAG_KEYFRAME
171 enqueue(Packet(if (isConfig) 0 else info.presentationTimeUs, flags, cfg.configGen, data))
172 }
173 codec.releaseOutputBuffer(index, false)
174 }
175 } finally {
176 currentCodec = null
177 runCatching { codec.stop() }
178 runCatching { codec.release() }
179 display.release()
180 surface.release()
181 }
182 }
183
184 /** 송신이 밀리면 비키프레임을 버리고 다음 키프레임까지 기다린다 (지연 우선). */
185 private fun enqueue(p: Packet) {
186 val important = p.flags and (FLAG_CONFIG or FLAG_KEYFRAME) != 0
187 if (important) {
188 if (p.flags and FLAG_KEYFRAME != 0) waitingKeyframe = false
189 queue.put(p)
190 return
191 }
192 if (waitingKeyframe) return
193 if (!queue.offer(p)) {
194 waitingKeyframe = true
195 requestKeyframe()
196 }
197 }
198
199 private fun writeLoop() {
200 val header = ByteBuffer.allocate(Protocol.VIDEO_HEADER_LEN)
201 try {
202 while (running) {
203 val p = queue.poll(200, TimeUnit.MILLISECONDS) ?: continue
204 header.clear()
205 header.putLong(p.ptsUs).put(p.flags.toByte()).put(p.gen.toByte()).putShort(0).putInt(p.data.size)
206 output.write(header.array())
207 output.write(p.data)
208 output.flush()
209 }
210 } catch (e: InterruptedException) {
211 // 정상 종료
212 } catch (e: IOException) {
213 Log.i("$peer: 영상 송신 종료 (${e.message})")
214 } finally {
215 running = false
216 encoderThread?.interrupt()
217 }
218 }
219
220 companion object {
221 const val FLAG_CONFIG = 0x01
222 const val FLAG_KEYFRAME = 0x02
223 private const val QUEUE_LIMIT = 4
224 private const val KEYFRAME_INTERVAL_S = 10
225 private const val REPEAT_AFTER_US = 100_000L
226 private const val DEQUEUE_TIMEOUT_US = 50_000L
227 private const val ROTATION_CHECK_MS = 250L
228 }
229}
230
231/**
232 * 기본 디스플레이(0)를 인코더 입력 Surface로 미러링한다. Android 14+의 숨은
233 * DisplayManager.createVirtualDisplay(이름, 너비, 높이, 미러링할 디스플레이, Surface)를 먼저 쓰고,
234 * 실패하면 SurfaceControl 방식으로 대체한다.
235 */
236object DisplayCapture {
237 class Handle(val method: String, private val onRelease: () -> Unit) {
238 fun release() = runCatching { onRelease() }.let { }
239 }
240
241 fun mirror(name: String, width: Int, height: Int, displayWidth: Int, displayHeight: Int, surface: Surface): Handle {
242 try {
243 val m = DisplayManager::class.java.getMethod(
244 "createVirtualDisplay",
245 String::class.java, Int::class.javaPrimitiveType, Int::class.javaPrimitiveType,
246 Int::class.javaPrimitiveType, Surface::class.java,
247 )
248 val vd = m.invoke(null, name, width, height, 0, surface) as VirtualDisplay
249 return Handle("DisplayManager") { vd.release() }
250 } catch (e: Exception) {
251 Log.w("DisplayManager 미러링 실패, SurfaceControl로 대체: ${e.cause ?: e}")
252 }
253
254 val sc = Class.forName("android.view.SurfaceControl")
255 val token = sc.getMethod("createDisplay", String::class.java, Boolean::class.javaPrimitiveType)
256 .invoke(null, name, false) as IBinder
257 sc.getMethod("openTransaction").invoke(null)
258 try {
259 sc.getMethod("setDisplaySurface", IBinder::class.java, Surface::class.java).invoke(null, token, surface)
260 sc.getMethod("setDisplayProjection", IBinder::class.java, Int::class.javaPrimitiveType, Rect::class.java, Rect::class.java)
261 .invoke(null, token, 0, Rect(0, 0, displayWidth, displayHeight), Rect(0, 0, width, height))
262 sc.getMethod("setDisplayLayerStack", IBinder::class.java, Int::class.javaPrimitiveType).invoke(null, token, 0)
263 } finally {
264 sc.getMethod("closeTransaction").invoke(null)
265 }
266 return Handle("SurfaceControl") {
267 sc.getMethod("destroyDisplay", IBinder::class.java).invoke(null, token)
268 }
269 }
270}