Fix(android): correct lock/input state and recover screen capture
db148c4 asked KeyguardManager on every heartbeat; some TVs answer "locked"
while playing video, so hosts showed "Locked: HH:MM:SS" forever and the
foreground app never reached the server. Lock state is event-driven again:
SCREEN_OFF records the start, USER_PRESENT clears it, and on SCREEN_ON the
state clears when the device is TV-like or has no keyguard (devices without
a lock screen never send USER_PRESENT); a phone that reconnects while
locked is re-calibrated the same way. Keyguard is consulted only at those
event points, never per heartbeat.
Input strategy and TV heuristics are separate immutable values: isTV (D-pad
focus navigation vs touch injection) only looks at leanback, isTvLike (lock
and encoder heuristics) also accepts television/uiMode. They were once
merged and the TV lost remote control, then an assignment was dropped and
it silently defaulted to false; immutable lazy values make both impossible.
The resolved mode is logged as "input=dpad|touch tvLike=..." and mirrored
into the native ring when available.
Screen capture: on TVs the default encoder configuration is tried first.
After a sleep the existing VirtualDisplay stops composing while the
projection stays alive, so a 5s zero-frame stall rebuilds the encoder and
VirtualDisplay on the same projection (reusing the session's encoded size),
requests a fresh IDR and reports failure only after 13s; if the projection
is gone the native size is cleared so the next request re-authorizes. A
repeated onStartCommand no longer calls nativeInit again (the -1 answer
used to stopSelf and drop the host). Kotlin capture logs mirror into the
native ring and fall back to logcat.
Debug APK builds; device verification pending.
Co-Authored-By: deepseek-flash
This commit was merged in pull request #8.
This commit is contained in:
1 parent
be19744898
commit
340fb20518
6 files changed
+392
-74
No files matched your search
@@ -23,6 +23,7 @@ import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.provider.Settings
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
@@ -31,6 +32,18 @@ import android.widget.Toast
|
||||
|
||||
import java.nio.charset.Charset
|
||||
|
||||
// 关键日志同时写进 native 的 Logger ring(服务端「运行日志」/ MCP get_client_log 可导出)。
|
||||
// 电视等没有 adb 的设备上,这是唯一能把编码器状态带回主控的通道。
|
||||
// native 库没加载成功时退回落 logcat——否则「Native library load failed」这类
|
||||
// 关键错误反而看不到(那次调用本身就依赖 native 库)。
|
||||
private fun ylog(priority: Int, msg: String) {
|
||||
val ok = runCatching { YamaBridge.nativeLog(priority, "YAMA", msg) }.isSuccess
|
||||
if (!ok) Log.println(priority, "YAMA", msg)
|
||||
}
|
||||
private fun ylogI(msg: String) = ylog(Log.INFO, msg)
|
||||
private fun ylogW(msg: String) = ylog(Log.WARN, msg)
|
||||
private fun ylogE(msg: String) = ylog(Log.ERROR, msg)
|
||||
private fun ylogD(msg: String) = ylog(Log.DEBUG, msg)
|
||||
class CaptureService : Service() {
|
||||
|
||||
companion object {
|
||||
@@ -38,6 +51,9 @@ class CaptureService : Service() {
|
||||
const val CHANNEL_ID = "yama_service"
|
||||
const val NOTIF_ID = 1
|
||||
|
||||
// 采集零输出时重建管线的节流时间戳(毫秒)
|
||||
@Volatile private var lastStallRestartMs = 0L
|
||||
|
||||
const val EXTRA_SERVER_IP = "server_ip"
|
||||
const val EXTRA_SERVER_PORT = "server_port"
|
||||
const val EXTRA_PROJECTION_RESULT = "projection_result"
|
||||
@@ -63,7 +79,7 @@ class CaptureService : Service() {
|
||||
@JvmStatic
|
||||
fun onUpdateReceived(path: String) {
|
||||
val ctx = instance ?: appContext ?: return
|
||||
Log.i(TAG, "onUpdateReceived: $path")
|
||||
ylogI("onUpdateReceived: $path")
|
||||
UpdateInstaller.onApkReceived(ctx, path)
|
||||
}
|
||||
|
||||
@@ -71,7 +87,7 @@ class CaptureService : Service() {
|
||||
@JvmStatic
|
||||
fun onUninstallRequested() {
|
||||
val ctx = instance ?: appContext ?: return
|
||||
Log.i(TAG, "onUninstallRequested")
|
||||
ylogI("onUninstallRequested")
|
||||
Uninstaller.request(ctx)
|
||||
}
|
||||
|
||||
@@ -85,12 +101,12 @@ class CaptureService : Service() {
|
||||
fun onClipboardText(bytes: ByteArray) {
|
||||
val ctx = instance ?: appContext
|
||||
if (ctx == null) {
|
||||
Log.w(TAG, "onClipboardText: no context, ${bytes.size} bytes dropped")
|
||||
ylogW("onClipboardText: no context, ${bytes.size} bytes dropped")
|
||||
return
|
||||
}
|
||||
val cm = ctx.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
||||
if (cm == null) {
|
||||
Log.e(TAG, "onClipboardText: no ClipboardManager")
|
||||
ylogE("onClipboardText: no ClipboardManager")
|
||||
return
|
||||
}
|
||||
// 人类剪贴板同步(ScreenSpyDlg / HideScreenSpyDlg)发的是带 '\0' 结尾的 CF_TEXT,
|
||||
@@ -98,17 +114,17 @@ class CaptureService : Service() {
|
||||
val text = String(bytes, Charset.forName("GBK")).trimEnd('\u0000')
|
||||
try {
|
||||
cm.setPrimaryClip(ClipData.newPlainText("YAMA", text))
|
||||
Log.i(TAG, "onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
||||
ylogI("onClipboardText: ${bytes.size} bytes, ${text.length} chars")
|
||||
} catch (e: Throwable) {
|
||||
// Android 10+ 极少见地会在某些受限场景抛 SecurityException;记日志不崩 JNI 线程
|
||||
Log.e(TAG, "onClipboardText: setPrimaryClip failed: $e")
|
||||
ylogE("onClipboardText: setPrimaryClip failed: $e")
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun onNativeExit() {
|
||||
val svc = instance ?: return
|
||||
Log.i(TAG, "onNativeExit: server requested disconnect, stopping service")
|
||||
ylogI("onNativeExit: server requested disconnect, stopping service")
|
||||
svc.idrHandler.post { svc.stopSelf() }
|
||||
}
|
||||
|
||||
@@ -140,8 +156,8 @@ class CaptureService : Service() {
|
||||
p.putInt(MediaCodec.PARAMETER_KEY_VIDEO_BITRATE, kbps * 1000)
|
||||
codec.setParameters(p)
|
||||
svc.currentBitRateKbps = kbps
|
||||
Log.i(TAG, "bitrate -> $kbps kbps")
|
||||
}.onFailure { Log.e(TAG, "bitrate change to $kbps failed: $it") }
|
||||
ylogI("bitrate -> $kbps kbps")
|
||||
}.onFailure { ylogE("bitrate change to $kbps failed: $it") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,17 +176,93 @@ class CaptureService : Service() {
|
||||
val w = ControlService.encW
|
||||
val h = ControlService.encH
|
||||
val dpi = svc.resources.displayMetrics.densityDpi
|
||||
Log.d(TAG, "forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
||||
ylogD("forceFirstFrame: resize ${w}x${h} → ${w+2}x${h} to trigger composition")
|
||||
vd.resize(w + 2, h, dpi)
|
||||
svc.idrHandler.postDelayed({
|
||||
runCatching { vd.resize(w, h, dpi) }
|
||||
Log.d(TAG, "forceFirstFrame: restored ${w}x${h}")
|
||||
ylogD("forceFirstFrame: restored ${w}x${h}")
|
||||
}, 150)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 远程桌面请求时没有可用的投影会话(Android TV 从未授权,或 Android 14 的单次
|
||||
* 授权在服务重启后失效):尝试拉起 MainActivity 重新走一遍系统「屏幕捕获」授权。
|
||||
* 优先用无障碍服务的 startActivity——系统绑定服务不受后台启动 Activity 限制。
|
||||
* 调用方是 native 的 ScreenSpyThread(g_requestPermMid),10 分钟内最多触发一次。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun requestScreenCapturePermission() {
|
||||
val ctx = appContext ?: instance ?: return
|
||||
// request_projection:MainActivity 还活着时走 onNewIntent,靠这个 extra 重新发起授权;
|
||||
// 也避免把用户主动点图标打开 App 的情况误判成授权请求。
|
||||
val intent = Intent(ctx, MainActivity::class.java)
|
||||
// SINGLE_TOP:MainActivity 还活着且位于栈顶时走 onNewIntent 重新授权;
|
||||
// 没有它,NEW_TASK 只是把任务前置,既不走 onCreate 也不走 onNewIntent,
|
||||
// 授权界面永远弹不出来。
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
.putExtra(MainActivity.EXTRA_REQUEST_PROJECTION, true)
|
||||
val acc = ControlService.instance
|
||||
// AccessibilityService.startActivity(Intent) 是 API 24+;minSdk 21 上会抛
|
||||
// NoSuchMethodError,失败时回退到普通 startActivity。
|
||||
var launched = false
|
||||
if (acc != null) launched = runCatching { acc.startActivity(intent) }.isSuccess
|
||||
if (!launched) launched = runCatching { ctx.startActivity(intent) }.isSuccess
|
||||
ylogI("screen-capture permission prompt: launched=$launched")
|
||||
}
|
||||
|
||||
/**
|
||||
* SendLoop 检测到「采集在跑、但编码器零输出」时调用(电视睡眠后最常见:
|
||||
* MediaProjection 还在,SurfaceFlinger 却不再往旧的 VirtualDisplay 送帧)。
|
||||
* 用同一个 MediaProjection 重建编码器 + 虚拟显示(token 不消耗、无需重新授权);
|
||||
* 投影本身已经失效时把 native 尺寸清零,让下一次远程桌面重新走授权。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onEncoderStalled() {
|
||||
val svc = instance ?: return
|
||||
svc.idrHandler.post {
|
||||
val now = SystemClock.elapsedRealtime() // 单调时钟:墙上时间回拨不会让节流永久失效
|
||||
// last==0 是「本次开机还没重建过」:单调时钟 0 点是开机,开机 30 秒内
|
||||
// 不能因为 now-0 < 30000 就把第一次自愈吞掉。
|
||||
if (lastStallRestartMs != 0L && now - lastStallRestartMs < 30_000) return@post
|
||||
lastStallRestartMs = now
|
||||
val mp = svc.mediaProjection
|
||||
if (mp == null) {
|
||||
ylogI("capture stalled: projection gone, clearing screen size")
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
return@post
|
||||
}
|
||||
val (pw, ph) = svc.getPhysicalResolution()
|
||||
// 复用当前会话的编码尺寸,避免主控端解码器与新的 SPS 尺寸不一致。
|
||||
val keep = if (ControlService.encW > 0 && ControlService.encH > 0)
|
||||
Pair(ControlService.encW, ControlService.encH) else null
|
||||
ylogI("capture stalled: rebuilding encoder/virtual display (phys=${pw}x${ph}, keepEnc=${keep != null})")
|
||||
svc.releaseCaptureKeepProjection()
|
||||
val rebuilt = runCatching {
|
||||
svc.startCapture(mp, pw, ph, registerProjectionCallback = false, forcedEnc = keep)
|
||||
}.onFailure { ylogE("capture rebuild threw: $it") }.isSuccess
|
||||
// startCapture 先赋值 mediaCodec、后调 createVirtualDisplay;投影失效时
|
||||
// createVirtualDisplay 会抛异常,所以单看 mediaCodec 判不出失败。半初始化的
|
||||
// 编码器必须收干净、native 尺寸清零,否则后续远程桌面会一直带着旧尺寸停在
|
||||
// 「请等待」,也不会走重新授权。
|
||||
if (!rebuilt || svc.mediaCodec == null || svc.virtualDisplay == null) {
|
||||
ylogE("capture rebuild failed; clearing screen size")
|
||||
svc.releaseCaptureKeepProjection()
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
} else {
|
||||
// 静止画面(电视停在桌面/暂停的视频)没有任何脏区,新 VirtualDisplay
|
||||
// 不会合成出帧。和首条管线一样,用一次 ±2px resize 触发合成。
|
||||
forceFirstFrame()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// nativeInit 是否已完成。MainActivity 重新授权会再次 startForegroundService,同一个
|
||||
// Service 实例会收到第二次 onStartCommand:这时不能再次 nativeInit(main.cpp 的 CAS
|
||||
// 会返回 -1),否则失败分支会 stopSelf → nativeStop → 客户端直接掉线。
|
||||
private var nativeReady = false
|
||||
private var mediaProjection: MediaProjection? = null
|
||||
private var virtualDisplay: VirtualDisplay? = null
|
||||
private var mediaCodec: MediaCodec? = null
|
||||
@@ -220,29 +312,39 @@ class CaptureService : Service() {
|
||||
val res = "1:${sw}*${sh}"
|
||||
val user = Build.USER
|
||||
|
||||
// 初始化前不能走 ylog*/YamaBridge:那会触发 loadLibrary,失败时把类初始化搞坏,
|
||||
// 后面的 nativeInit 会变成 NoClassDefFoundError(不是下面两个 catch 能接住的)。
|
||||
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
|
||||
|
||||
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
|
||||
// ExceptionInInitializerError 包裹 UnsatisfiedLinkError(首次访问 object 时触发)
|
||||
val initRet: Int
|
||||
try {
|
||||
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "", filesDir.absolutePath,
|
||||
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.e(TAG, "Native library load failed: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: ExceptionInInitializerError) {
|
||||
Log.e(TAG, "Native library init failed: ${e.cause}")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
if (!nativeReady) {
|
||||
var initRet = 0
|
||||
try {
|
||||
initRet = YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user,
|
||||
packageCodePath ?: "", filesDir.absolutePath,
|
||||
BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE)
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
ylogE("Native library load failed: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: ExceptionInInitializerError) {
|
||||
ylogE("Native library init failed: ${e.cause}")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
} catch (e: Throwable) {
|
||||
// 类初始化失败后再次访问 YamaBridge 会抛 NoClassDefFoundError
|
||||
ylogE("nativeInit threw: $e")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (initRet != 0 && initRet != -1) { // -1 = 已在运行(重复 start),不算失败
|
||||
ylogE("nativeInit failed: ret=$initRet")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
nativeReady = true
|
||||
}
|
||||
if (initRet != 0) {
|
||||
Log.e(TAG, "nativeInit failed: ret=$initRet")
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
val projResult = intent.getIntExtra(EXTRA_PROJECTION_RESULT, -1)
|
||||
val projData = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
|
||||
intent.getParcelableExtra(EXTRA_PROJECTION_DATA, Intent::class.java)
|
||||
@@ -266,7 +368,7 @@ class CaptureService : Service() {
|
||||
// codec/vd 会漏掉它,旧 projection 永不 stop(),投屏指示器一直亮着,
|
||||
// 它的 onStop 回调也继续挂着。
|
||||
if (mediaCodec != null || virtualDisplay != null || mediaProjection != null) {
|
||||
Log.i(TAG, "onStartCommand: releasing previous capture before restart")
|
||||
ylogI("onStartCommand: releasing previous capture before restart")
|
||||
stopCapture()
|
||||
}
|
||||
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
@@ -277,13 +379,13 @@ class CaptureService : Service() {
|
||||
try {
|
||||
startCapture(mp, sw, sh)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Screen capture failed: $e — running without capture")
|
||||
ylogE("Screen capture failed: $e — running without capture")
|
||||
}
|
||||
} else {
|
||||
Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||
ylogE("Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "No MediaProjection token, skipping screen capture")
|
||||
ylogW("No MediaProjection token, skipping screen capture")
|
||||
}
|
||||
|
||||
return START_STICKY
|
||||
@@ -293,23 +395,34 @@ class CaptureService : Service() {
|
||||
super.onDestroy()
|
||||
instance = null
|
||||
stopCapture()
|
||||
YamaBridge.nativeStop()
|
||||
Log.i(TAG, "CaptureService destroyed")
|
||||
// nativeInit 没成功过就不要碰 YamaBridge(类初始化失败后会抛 NoClassDefFoundError)
|
||||
ylogI("CaptureService destroyed")
|
||||
if (nativeReady) runCatching { YamaBridge.nativeStop() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- MediaProjection + MediaCodec
|
||||
|
||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) {
|
||||
val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int, registerProjectionCallback: Boolean = true, forcedEnc: Pair<Int, Int>? = null) {
|
||||
// 重建时必须沿用原会话的编码尺寸:主控端的解码器已按最初的 BITMAPINFO 初始化,
|
||||
// 睡眠后物理分辨率可能变化(实测 1080x606 → 1280x720),重新推导可能得到不同的
|
||||
// 编码尺寸,主控端会黑屏。forcedEnc 由 onEncoderStalled 传入。
|
||||
val (encW, encH) = forcedEnc ?: scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
|
||||
// 主控端上次保存的档位决定开抓码率;自适应档从 Good 起步(与服务端假设一致)
|
||||
val (bitRateKbps, fps) = ScreenTuning.startupRate()
|
||||
Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
||||
ylogI("Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi " +
|
||||
"bitrate=${bitRateKbps}kbps fps=$fps level=${ScreenTuning.getQualityLevel()}")
|
||||
|
||||
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
||||
val surface = configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
||||
// configureEncoder 三套配置都失败时会抛异常;此时 mediaCodec 还没赋值,
|
||||
// releaseCaptureKeepProjection 收不到它,必须在这里释放,否则每次重建失败都漏一个编码器。
|
||||
val surface = try {
|
||||
configureEncoder(codec, encW, encH, bitRateKbps, fps)
|
||||
} catch (e: Exception) {
|
||||
runCatching { codec.release() }
|
||||
throw e
|
||||
}
|
||||
currentBitRateKbps = bitRateKbps
|
||||
|
||||
var configData: ByteArray? = null
|
||||
@@ -345,31 +458,37 @@ class CaptureService : Service() {
|
||||
}
|
||||
|
||||
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
|
||||
Log.e(TAG, "MediaCodec error: $e")
|
||||
ylogE("MediaCodec error: $e")
|
||||
}
|
||||
|
||||
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
|
||||
Log.i(TAG, "Output format: $format")
|
||||
ylogI("Output format: $format")
|
||||
}
|
||||
})
|
||||
|
||||
codec.start()
|
||||
try {
|
||||
codec.start()
|
||||
} catch (e: Exception) {
|
||||
// 同上:start 抛异常时 mediaCodec 还没赋值,编码器会漏掉
|
||||
runCatching { codec.release() }
|
||||
throw e
|
||||
}
|
||||
mediaCodec = codec
|
||||
|
||||
idrHandler.postDelayed(idrRunnable, 500)
|
||||
|
||||
// Android 14+ requires callback registered before createVirtualDisplay()
|
||||
mp.registerCallback(object : MediaProjection.Callback() {
|
||||
if (registerProjectionCallback) mp.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
// stop() 的回调是异步投递到主线程的,可能在新一轮 startCapture 之后
|
||||
// 才到达。身份不一致说明这是被我们主动收掉的旧 projection,忽略它,
|
||||
// 否则迟到的回调会把刚建好的 VirtualDisplay 和编码器一起拆掉。
|
||||
// 顺带也让 stopCapture() 内部的 mp.stop() 不再递归触发自己。
|
||||
if (mediaProjection !== mp) {
|
||||
Log.i(TAG, "stale MediaProjection onStop ignored")
|
||||
ylogI("stale MediaProjection onStop ignored")
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "MediaProjection stopped — switching to dataSync foreground type")
|
||||
ylogI("MediaProjection stopped — switching to dataSync foreground type")
|
||||
stopCapture()
|
||||
// Android 14+: system auto-kills a foreground service whose mediaProjection
|
||||
// is revoked. Re-declare as dataSync-only to survive without screen capture.
|
||||
@@ -387,7 +506,7 @@ class CaptureService : Service() {
|
||||
// ScreenSpyThread 认为投屏就绪、照常发 BITMAPINFO,而 surface 没有任何生产者,
|
||||
// 编码器永远不输出 → 服务端停在"请等待"。这里必须显式失败,不能静默。
|
||||
if (vd == null) {
|
||||
Log.e(TAG, "createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
|
||||
ylogE("createVirtualDisplay returned null (enc=${encW}x${encH} dpi=$dpi) — " +
|
||||
"no frames will be produced; check MediaProjection token")
|
||||
// 500ms 前已经 postDelayed 过 idrRunnable,不收掉它会每秒空转(mediaCodec
|
||||
// 已置 null,setParameters 是 null-safe,但没意义)。
|
||||
@@ -419,7 +538,7 @@ class CaptureService : Service() {
|
||||
ControlService.encW = encW
|
||||
ControlService.encH = encH
|
||||
|
||||
Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||
ylogI("MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||
}
|
||||
|
||||
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean,
|
||||
@@ -449,22 +568,26 @@ class CaptureService : Service() {
|
||||
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
|
||||
}
|
||||
|
||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容
|
||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容。
|
||||
// 电视(isTvDevice:leanback/television/uiMode)的硬件编码器对低延迟配置尤其敏感:
|
||||
// configure/createInputSurface/start 全部成功,但 KEY_LOW_LATENCY 下可能一帧都不输出
|
||||
// (与 KEY_OPERATING_RATE 压到 30 以下同类的低功耗行为)。电视上因此先试「默认配置」,
|
||||
// 手机保持原顺序。注意这与 D-pad 输入策略的 leanback 判定是两件事。
|
||||
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int,
|
||||
bitRateKbps: Int, fps: Int): android.view.Surface {
|
||||
val configs = listOf(
|
||||
true to true,
|
||||
true to false,
|
||||
false to false,
|
||||
)
|
||||
val isTv = ControlService.isTvDevice(this)
|
||||
val configs = if (isTv)
|
||||
listOf(false to false, true to false, true to true)
|
||||
else
|
||||
listOf(true to true, true to false, false to false)
|
||||
for ((ll, bl) in configs) {
|
||||
try {
|
||||
val fmt = buildFmt(w, h, ll, bl, bitRateKbps, fps)
|
||||
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||
Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl")
|
||||
ylogI("Encoder configured: lowLatency=$ll baseline=$bl")
|
||||
return codec.createInputSurface()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||
ylogW("Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||
try { codec.reset() } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
@@ -487,7 +610,21 @@ class CaptureService : Service() {
|
||||
// 客户端照常建子连接、发 TOKEN_BITMAPINFO,服务端收到尺寸后进入"请等待",而
|
||||
// 编码器一帧都产不出来 → 永远停在"请等待"。token 是一次性的,客户端自己恢复
|
||||
// 不了,只能重新走授权,所以这里唯一正确的动作是如实报告「没有投屏」。
|
||||
YamaBridge.nativeSetScreenSize(0, 0)
|
||||
// native 初始化失败时(onDestroy 仍会走到这里)碰 YamaBridge 会抛
|
||||
// NoClassDefFoundError,必须由 nativeReady 挡住。
|
||||
if (nativeReady) runCatching { YamaBridge.nativeSetScreenSize(0, 0) }
|
||||
}
|
||||
|
||||
// 只拆编码器与虚拟显示、保留 MediaProjection:Android 14 的投影 token 是一次性的,
|
||||
// stop() 之后就只能重新授权。电视睡眠后旧的 VirtualDisplay 收不到合成帧时,用同一个
|
||||
// 投影重建一条新的虚拟显示即可恢复,不必打扰设备前的用户。
|
||||
private fun releaseCaptureKeepProjection() {
|
||||
idrHandler.removeCallbacks(idrRunnable)
|
||||
runCatching { virtualDisplay?.release() }
|
||||
runCatching { mediaCodec?.stop() }
|
||||
runCatching { mediaCodec?.release() }
|
||||
virtualDisplay = null
|
||||
mediaCodec = null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 辅助函数
|
||||
@@ -564,10 +701,10 @@ class CaptureService : Service() {
|
||||
try {
|
||||
startForeground(NOTIF_ID, buildNotification(), types)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "startForeground(types=0x${types.toString(16)}) failed: $e")
|
||||
ylogE("startForeground(types=0x${types.toString(16)}) failed: $e")
|
||||
if (types != base) {
|
||||
runCatching { startForeground(NOTIF_ID, buildNotification(), base) }
|
||||
.onFailure { Log.e(TAG, "startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
||||
.onFailure { ylogE("startForeground(base=0x${base.toString(16)}) also failed: $it") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user