diff --git a/.gitignore b/.gitignore index 64280ec..13e0995 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,4 @@ desktop.ini # ===== Logs ===== *.log +android_receiver/.remotecompile/ diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt index 8439450..63b5c01 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MainActivity.kt @@ -9,6 +9,7 @@ import android.os.Looper import android.widget.Button import android.widget.LinearLayout import android.widget.TextView +import android.widget.Toast import com.ttstd.lancast.receiver.discovery.HostBeacon import com.ttstd.lancast.receiver.session.PairingCode import java.net.NetworkInterface @@ -78,6 +79,12 @@ class MainActivity : Activity() { }.start() start.setOnClickListener { + // 系统同一时刻只允许一路 MediaProjection:会话进行中再次授权会让正在采集的 + // 那一路失效(non-current MediaProjection),必须等停止后再重新授权。 + if (MediaProjectionService.isRunning) { + Toast.makeText(this, "投屏已在进行中,请先点「停止」", Toast.LENGTH_SHORT).show() + return@setOnClickListener + } val manager = getSystemService(MediaProjectionManager::class.java) startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_CAPTURE) } diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt index c8f1bb6..01019d7 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/MediaProjectionService.kt @@ -65,6 +65,22 @@ class MediaProjectionService : Service() { private var session: ReceiverSession? = null private var beacon: com.ttstd.lancast.receiver.discovery.HostBeacon? = null + /** 当前投影实例;必须持有引用,销毁时显式 stop(),否则会残留为「当前投影」。 */ + private var projection: MediaProjection? = null + private var projectionCallback: MediaProjection.Callback? = null + + /** 保护 [session] / [projection] / [generation] / [starting] 的状态锁。 */ + private val stateLock = Any() + + /** + * 会话世代号,每次启动或销毁时递增。后台启动线程持旧世代号时不再操作投影, + * 避免上一路 MediaProjection 已被新一路顶掉后仍去 createVirtualDisplay。 + */ + private var generation = 0 + + /** 正在创建投影 / 虚拟显示(尚未成功也未失败)。用于拦截重复启动请求。 */ + private var starting = false + override fun onCreate() { super.onCreate() createNotificationChannel() @@ -112,55 +128,100 @@ class MediaProjectionService : Service() { } private fun startProjectionSession(resultCode: Int, data: Intent, host: String, signalingUrl: String) { - stopProjectionSession() - try { - val manager = getSystemService(MediaProjectionManager::class.java) - val projection = manager.getMediaProjection(resultCode, data) - if (projection == null) { - Toast.makeText(this, "MediaProjection 授权失败", Toast.LENGTH_SHORT).show() - stopSelf() + val gen = synchronized(stateLock) { + // 系统同一时刻只允许一路 MediaProjection 处于活动状态:再调一次 getMediaProjection + // 会立刻让上一路失效,其 createVirtualDisplay 便抛 + // "Cannot create VirtualDisplay with non-current MediaProjection"。 + if (starting || session != null) { + Log.w(TAG, "忽略重复启动请求(starting=$starting, running=${session != null})") return } + starting = true + ++generation + } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - projection.registerCallback(object : MediaProjection.Callback() { - override fun onStop() { - Log.i(TAG, "MediaProjection session stopped by system") + val manager = getSystemService(MediaProjectionManager::class.java) + val created = try { + manager?.getMediaProjection(resultCode, data) + } catch (e: Exception) { + Log.e(TAG, "getMediaProjection failed", e) + null + } + if (created == null) { + Toast.makeText(this, "MediaProjection 授权失败,请重新授权", Toast.LENGTH_SHORT).show() + stopProjectionSession() + stopSelf() + return + } + + val callback = object : MediaProjection.Callback() { + override fun onStop() { + Log.i(TAG, "MediaProjection session stopped by system") + Handler(Looper.getMainLooper()).post { + // 只拆掉自己这一路,避免旧投影的回调把新会话拆了。 + if (isCurrentProjection(created)) { stopProjectionSession() stopSelf() } - }, Handler(Looper.getMainLooper())) - } - - startBeacon() - session = ReceiverSession( - context = this, - projection = projection, - hostOverride = host, - signalingUrl = signalingUrl, - certificatePem = "", - ) - // 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。 - Thread { - try { - session?.start() - isRunning = true - } catch (e: Exception) { - Log.e(TAG, "Failed to start receiver session", e) - Handler(Looper.getMainLooper()).post { - Toast.makeText(this@MediaProjectionService, "连接失败: ${e.message}", Toast.LENGTH_SHORT).show() - } - stopProjectionSession() - stopSelf() } - }.start() - } catch (e: Exception) { - Log.e(TAG, "Failed to start MediaProjection session", e) - Toast.makeText(this, "启动屏幕投影失败: ${e.message}", Toast.LENGTH_SHORT).show() - stopSelf() + } } + projection = created + projectionCallback = callback + created.registerCallback(callback, Handler(Looper.getMainLooper())) + + startBeacon() + val current = ReceiverSession( + context = this, + projection = created, + hostOverride = host, + signalingUrl = signalingUrl, + certificatePem = "", + ) + session = current + + // 连接建立包含 TCP 握手,必须在后台线程执行,避免服务主线程 ANR。 + Thread { + try { + if (!isCurrentGeneration(gen)) { + current.stop() + return@Thread + } + current.start() + if (!isCurrentGeneration(gen)) { + current.stop() + return@Thread + } + isRunning = true + synchronized(stateLock) { if (gen == generation) starting = false } + Log.i(TAG, "Receiver session started") + } catch (e: Throwable) { + // 用 Throwable 兜底,避免异常逃逸后 starting 卡在 true 让会话再也无法重建。 + Log.e(TAG, "Failed to start receiver session", e) + Handler(Looper.getMainLooper()).post { failStart(gen, e) } + } + }.start() } + /** 启动失败:只有仍是当前世代时才拆会话,避免误杀新会话。 */ + private fun failStart(gen: Int, error: Throwable) { + if (!isCurrentGeneration(gen)) return + val raw = error.message ?: error.javaClass.simpleName + val message = if (raw.contains("non-current", ignoreCase = true)) { + "投屏授权已失效,请重新点击「授权并开始投屏」" + } else { + raw + } + Toast.makeText(this, "连接失败: $message", Toast.LENGTH_SHORT).show() + stopProjectionSession() + stopSelf() + } + + private fun isCurrentGeneration(gen: Int): Boolean = synchronized(stateLock) { gen == generation } + + private fun isCurrentProjection(target: MediaProjection): Boolean = + synchronized(stateLock) { projection === target } + /** 开启 UDP 信标:一边广播自身,一边收集主控端的 host 应答。 */ private fun startBeacon() { if (beacon != null) return @@ -179,8 +240,29 @@ class MediaProjectionService : Service() { } private fun stopProjectionSession() { + synchronized(stateLock) { + // 递增世代号,让仍在启动流程里的后台线程失效,不再碰已被顶掉的投影。 + ++generation + starting = false + } session?.stop() session = null + + val callback = projectionCallback + val current = projection + projectionCallback = null + projection = null + if (callback != null && current != null) { + runCatching { current.unregisterCallback(callback) } + .onFailure { Log.w(TAG, "unregisterCallback failed", it) } + } + // 必须显式 stop():否则系统仍把上一路投影视为「当前」投影, + // 下一次 createVirtualDisplay 会抛 non-current MediaProjection。 + if (current != null) { + runCatching { current.stop() } + .onFailure { Log.w(TAG, "projection.stop() failed", it) } + } + beacon?.stop() beacon = null com.ttstd.lancast.receiver.discovery.HostBeacon.resetHost() diff --git a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt index d4db995..00e4d22 100644 --- a/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt +++ b/android_receiver/app/src/main/java/com/ttstd/lancast/receiver/ReceiverSession.kt @@ -59,11 +59,28 @@ class ReceiverSession( val width = maxOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1920) val height = minOf(metrics.widthPixels, metrics.heightPixels).coerceAtMost(1080) - encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265) - val surface = encoder.inputSurface ?: return - capturer = ScreenCapturer(projection, surface, metrics.densityDpi).also { it.start(width, height) } - clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) } + try { + startCapture(width, height, metrics.densityDpi) + startPublishing(width, height) + } catch (e: Exception) { + // 启动失败必须彻底释放已申请的编码器/虚拟显示,否则会残留并阻塞下次启动。 + running = false + stop() + throw e + } + } + /** 建立采集链路:编码器 + VirtualDisplay + 剪贴板。 */ + private fun startCapture(width: Int, height: Int, densityDpi: Int) { + encoder.start(width, height, 30, bitrateMbps * 1_000_000, preferH265) + val surface = encoder.inputSurface + ?: throw IllegalStateException("视频编码器未返回输入 Surface") + capturer = ScreenCapturer(projection, surface, densityDpi).also { it.start(width, height) } + clipboard.start { text -> transport?.sendControl(ControlEvent.Clipboard(text)) } + } + + /** 发布设备信息 / 音频采集 / 拨号线程。 */ + private fun startPublishing(width: Int, height: Int) { val device = AnnouncedDevice( id = UUID.randomUUID().toString(), name = "Android Receiver",