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
@@ -22,6 +22,11 @@
|
||||
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
|
||||
|
||||
extern uint64_t g_myClientID;
|
||||
// 定义在 main.cpp:把消息发进主控消息栏(TOKEN_CLIENT_MSG)。
|
||||
// 远程桌面编码器零输出时,主控端停在「请等待」,必须主动回一条说明。
|
||||
extern void SendClientMessageToMain(const char* title, const char* text);
|
||||
// 定义在 main.cpp:编码器零输出时让 Kotlin 用同一个 MediaProjection 重建采集管线。
|
||||
extern void NotifyEncoderStalled();
|
||||
// 定义在 main.cpp,供子连接的 OnReceive 调用
|
||||
extern void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY);
|
||||
extern void DispatchClipboardText(const uint8_t* data, size_t size);
|
||||
@@ -279,6 +284,7 @@ private:
|
||||
// 干等。改成带超时的等待,把「没有帧」和「帧被当 P 帧丢弃」区分开。
|
||||
const auto startTick = std::chrono::steady_clock::now();
|
||||
bool noFrameWarned = false;
|
||||
bool stallNotified = false;
|
||||
while (m_running) {
|
||||
std::unique_lock<std::mutex> lk(m_mutex);
|
||||
m_cond.wait_for(lk, std::chrono::seconds(1),
|
||||
@@ -289,12 +295,37 @@ private:
|
||||
// 只在「一帧都没发出去过」时告警。发过首帧之后队列空是正常的:电视
|
||||
// 停在 launcher 这类静止画面时 SurfaceFlinger 不产生脏区,编码器就没
|
||||
// 输入,5 秒不打新帧属于预期行为,不能报成编码器故障。
|
||||
const auto elapsed = std::chrono::steady_clock::now() - startTick;
|
||||
if (!noFrameWarned && m_started && !m_firstSent &&
|
||||
std::chrono::steady_clock::now() - startTick > std::chrono::seconds(5)) {
|
||||
elapsed > std::chrono::seconds(5)) {
|
||||
noFrameWarned = true;
|
||||
// 发消息/重建都是慢操作,不能拿着 m_mutex:生产者(编码回调)推帧要拿它。
|
||||
lk.unlock();
|
||||
LOGE_SH("SendLoop: no frame from MediaCodec after 5s — encoder is not producing "
|
||||
"(MediaProjection stopped, VirtualDisplay null, or unsupported %dx%d)",
|
||||
m_width, m_height);
|
||||
// 电视睡眠后常见:投影还在,但旧的 VirtualDisplay 收不到合成帧。先用同一个
|
||||
// MediaProjection 重建采集管线(不需要重新授权);重建结果由 Kotlin 侧记录。
|
||||
NotifyEncoderStalled();
|
||||
} else if (noFrameWarned && !stallNotified && m_started && !m_firstSent &&
|
||||
elapsed > std::chrono::seconds(13)) {
|
||||
stallNotified = true;
|
||||
// 自愈也没救回来:主控端停在「请等待……」,明确回一条消息说明原因。
|
||||
// 多个观看者各自 13 秒都会走到这里,进程内 60 秒只发一条,避免刷屏。
|
||||
lk.unlock();
|
||||
static std::atomic<long long> lastNotifyMs{0};
|
||||
const long long nowMs = std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
long long prevMs = lastNotifyMs.load();
|
||||
// 多个观看者各自 13 秒都会走到这里;进程内 60 秒只发一条,避免刷屏。
|
||||
// prevMs == 0 表示本次开机还没发过(steady_clock 的 0 点是开机)。
|
||||
if ((prevMs == 0 || nowMs - prevMs > 60 * 1000) &&
|
||||
lastNotifyMs.compare_exchange_strong(prevMs, nowMs)) {
|
||||
SendClientMessageToMain(
|
||||
"Remote desktop",
|
||||
"The device screen encoder produced no frame (hardware encoder may reject "
|
||||
"this size or config). Remote desktop cannot start.");
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -255,6 +255,8 @@ static jmethodID g_canOverlayMid = nullptr; // ControlService.canOverlay(
|
||||
static jclass g_captureClass = nullptr;
|
||||
static jmethodID g_requestIdrMid = nullptr;
|
||||
static jmethodID g_forceFirstFrameMid = nullptr;
|
||||
static jmethodID g_requestPermMid = nullptr; // CaptureService.requestScreenCapturePermission()
|
||||
static jmethodID g_onStalledMid = nullptr; // CaptureService.onEncoderStalled()
|
||||
static jmethodID g_statusMid = nullptr; // CaptureService.onNativeStatus(String)
|
||||
static jmethodID g_nativeExitMid = nullptr; // CaptureService.onNativeExit() — 服务端主动断开时停止服务
|
||||
static jmethodID g_updateReceivedMid = nullptr; // CaptureService.onUpdateReceived(String) — 升级 APK 已落盘
|
||||
@@ -1171,6 +1173,13 @@ static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid);
|
||||
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
|
||||
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
|
||||
|
||||
// ScreenHandler.h 的 SendLoop 用:编码器零输出时让 Kotlin 用同一个 MediaProjection
|
||||
// 重建采集管线(电视睡眠后旧 VirtualDisplay 收不到合成帧的常见场景)。
|
||||
void NotifyEncoderStalled()
|
||||
{
|
||||
CallCaptureStaticVoid(g_onStalledMid);
|
||||
}
|
||||
|
||||
// 向 CaptureService.onNativeStatus() 发送状态 Toast(连接线程诊断用)
|
||||
static void PostStatus(const char* msg) {
|
||||
LOGI("STATUS: %s", msg);
|
||||
@@ -1194,6 +1203,16 @@ static void PostStatus(const char* msg) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static void sendClientMsg(const char* title, const char* text); // 定义见在线升级段
|
||||
|
||||
// 上一次因「没有投影会话」而拉起设备端授权界面的时间(单调毫秒)
|
||||
static std::atomic<long long> g_lastPermPromptMs{0};
|
||||
static long long MonotonicMs()
|
||||
{
|
||||
return (long long)std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
static void ScreenSpyThread()
|
||||
{
|
||||
// 等待 Java 侧 startCapture() 调用 nativeSetScreenSize 设置真实分辨率。
|
||||
@@ -1202,10 +1221,41 @@ static void ScreenSpyThread()
|
||||
for (int i = 0; i < 100 && g_screenWidth.load() == 0 && g_running.load(); ++i)
|
||||
Sleep(50); // 最多等 5 秒
|
||||
|
||||
if (g_screenWidth.load() == 0 && S_CLIENT_NORMAL == g_bExit) {
|
||||
// 投影没在跑:Android TV 可能从未授权,Android 14 的单次授权在服务重启后也会失效。
|
||||
// 尝试拉起设备上的 App 重新走一遍系统「屏幕捕获」授权,再等最多 15 秒。
|
||||
// 10 分钟内只提示一次,避免连续点远程桌面把电视反复弹到前台。
|
||||
const long long now = MonotonicMs();
|
||||
long long last = g_lastPermPromptMs.load();
|
||||
// steady_clock 的 0 点是开机时刻:last==0 表示「本次开机还没提示过」,必须放行,
|
||||
// 否则开机后前 10 分钟(正是最需要重新授权的场景)永远不会拉起授权界面。
|
||||
bool prompted = false;
|
||||
if ((last == 0 || now - last > 10 * 60 * 1000) &&
|
||||
g_lastPermPromptMs.compare_exchange_strong(last, now)) {
|
||||
prompted = true;
|
||||
LOGI("ScreenSpyThread: no projection; prompting device for screen-capture permission");
|
||||
CallCaptureStaticVoid(g_requestPermMid);
|
||||
}
|
||||
// 节流命中也可能是「另一个观看者刚刚拉起过授权框」:此时授权界面可能还显示在
|
||||
// 电视上,值得等一等,别让第二个观看者立刻收到"不可用"。只有 60 秒内的提示算
|
||||
// "可能还在屏幕上";更早的节流命中仍然立即失败,不让操作员白等。
|
||||
const bool promptRecentlyShown = (last != 0 && now - last <= 60 * 1000);
|
||||
if (prompted || promptRecentlyShown) {
|
||||
for (int i = 0; i < 300 && g_screenWidth.load() == 0 && g_running.load() && S_CLIENT_NORMAL == g_bExit; ++i)
|
||||
Sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
int w = g_screenWidth.load();
|
||||
int h = g_screenHeight.load();
|
||||
if (w == 0 || h == 0) {
|
||||
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
|
||||
// 服务端此时停在「请等待……」,收不到任何回应会一直挂着。这里必须明确回一条
|
||||
// 消息,说明是设备上的「屏幕捕获」授权/服务没在跑(常见于 Android TV:投影
|
||||
// 权限未授予,或服务被系统回收后需要重新打开 App 授权)。
|
||||
sendClientMsg("Remote desktop",
|
||||
"Screen capture is not available on this device. Open YAMA on the device, "
|
||||
"grant the screen-capture prompt, then try remote desktop again.");
|
||||
return;
|
||||
}
|
||||
std::string ip; int port;
|
||||
@@ -1894,6 +1944,13 @@ static void sendClientMsg(const char* title, const char* text)
|
||||
mc->Send2Server((char*)&msg, sizeof(msg));
|
||||
}
|
||||
|
||||
// ScreenHandler.h 的 SendLoop 用:编码器零输出时回主控消息栏。
|
||||
// 单独包一层是因为 sendClientMsg 是 static,头文件里只声明这个外部符号。
|
||||
void SendClientMessageToMain(const char* title, const char* text)
|
||||
{
|
||||
sendClientMsg(title, text);
|
||||
}
|
||||
|
||||
static void reportUpdateFailure(const std::string& reason)
|
||||
{
|
||||
LOGI("UPDATE failed: %s", reason.c_str());
|
||||
@@ -2926,6 +2983,12 @@ Java_com_yama_client_YamaBridge_nativeInit(
|
||||
g_forceFirstFrameMid = env->GetStaticMethodID(g_captureClass, "forceFirstFrame", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_forceFirstFrameMid = nullptr; }
|
||||
if (!g_forceFirstFrameMid) LOGE("CaptureService.forceFirstFrame not found");
|
||||
g_requestPermMid = env->GetStaticMethodID(g_captureClass, "requestScreenCapturePermission", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_requestPermMid = nullptr; }
|
||||
if (!g_requestPermMid) LOGE("CaptureService.requestScreenCapturePermission not found");
|
||||
g_onStalledMid = env->GetStaticMethodID(g_captureClass, "onEncoderStalled", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_onStalledMid = nullptr; }
|
||||
if (!g_onStalledMid) LOGE("CaptureService.onEncoderStalled not found");
|
||||
g_statusMid = env->GetStaticMethodID(g_captureClass, "onNativeStatus", "(Ljava/lang/String;)V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_statusMid = nullptr; }
|
||||
if (!g_statusMid) LOGE("CaptureService.onNativeStatus not found");
|
||||
@@ -3105,6 +3168,21 @@ Java_com_yama_client_YamaBridge_nativeInit(
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Kotlin 侧日志镜像:写进 logcat + Logger 内存 ring,服务端「运行日志」能取回。
|
||||
// 没有 adb 的电视/机顶盒只能靠这条通道把编码器状态带回主控。
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeLog(JNIEnv* env, jobject, jint prio, jstring tag, jstring msg)
|
||||
{
|
||||
if (!env || !msg) return;
|
||||
const char* t = tag ? env->GetStringUTFChars(tag, nullptr) : nullptr;
|
||||
const char* m = env->GetStringUTFChars(msg, nullptr);
|
||||
if (m) {
|
||||
android_log_tag((int)prio, t ? t : "YAMA", "%s", m);
|
||||
env->ReleaseStringUTFChars(msg, m);
|
||||
}
|
||||
if (t) env->ReleaseStringUTFChars(tag, t);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
|
||||
{
|
||||
@@ -3172,6 +3250,10 @@ Java_com_yama_client_YamaBridge_nativeAudioSendPcm(JNIEnv* env, jobject, jshortA
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
|
||||
{
|
||||
// 上报了非零尺寸 = 当前已有可用的投影会话:清掉「上次拉起授权」的节流时间。
|
||||
// 否则投影在 10 分钟内再次失效(睡眠/服务重启,正是这条路径存在的场景)时,
|
||||
// 节流会挡住第二次授权提示,客户端只能直接报「screen capture is not available」。
|
||||
if (width > 0) g_lastPermPromptMs.store(0);
|
||||
g_screenWidth.store(width);
|
||||
g_screenHeight.store(height);
|
||||
LOGI("ScreenSize=%dx%d", width, height);
|
||||
|
||||
Reference in new issue
Block a user