leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 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 | } |