The Android client dropped CMD_QUALITY_LEVEL, CMD_FPS, CMD_QUALITY_PROFILES and CMD_SCREEN_TUNING as log lines, and hardcoded ScreenSettings.QualityLevel to Good. Because the server initializes adaptive quality from the client's reported level, that hardcoded value pinned every Android session to a fixed profile: adaptive quality could never start. ScreenTuning.kt now owns the state in SharedPreferences (level, max fps and the master's six-row profile table), and C++ only parses the wire format. The level is persisted when the master sets it explicitly, including -1 adaptive and -2 disabled, and is reported back in TOKEN_BITMAPINFO on the next screen session. A concrete level switch applies the profile bitrate at runtime via MediaCodec.setParameters(PARAMETER_KEY_VIDEO_BITRATE), which is smooth and needs no encoder rebuild. Frame rate is stored as-is (255 = unlimited, matching Windows) and only reaches KEY_FRAME_RATE at the next capture start, since surface encoders have no runtime fps cap. Ultra and High default to a zero bitrate because their Windows algorithms are DIFF/RGB565, so Android falls back to the previous 4000 kbps. CMD_SCREEN_TUNING stays log-only: all four flags belong to the Windows capture/x264 path and Android does not claim SCREEN_CAP_TUNING_FLAGS. CMD_SCREEN_SIZE is ignored; the server's pending resolution-change mark self-heals after one second. Verified on the emulator: a seeded Level 5 starts capture at 800 kbps/8 fps and the server title shows Minimal; a master-side switch to Good changes the live bitrate to 3000, and a restart picks up fps 30 from CMD_FPS. Co-Authored-By: deepseek-flash
308 lines
14 KiB
C++
308 lines
14 KiB
C++
#pragma once
|
||
// Android 屏幕处理器:管理截屏子连接,接收 Java 侧 MediaCodec 输出的 H.264 NALU,
|
||
// 按协议封装后通过子连接发送给服务端。
|
||
#include "common/commands.h"
|
||
#include "common/logger.h"
|
||
#include "client/IOCPClient.h"
|
||
#include <atomic>
|
||
#include <mutex>
|
||
#include <condition_variable>
|
||
#include <queue>
|
||
#include <vector>
|
||
#include <thread>
|
||
#include <cstring>
|
||
#include <string>
|
||
#include <cinttypes>
|
||
#include <android/log.h>
|
||
|
||
// 与 main.cpp 的 LOGI/LOGE 同理:进 logcat 的同时进 Logger 内存 ring(MCP get_client_log)。
|
||
// 抓屏链路的问题(黑屏、码率)只能靠这些日志定位,必须能被主控取到。
|
||
#define LOGI_SH(...) android_log_tag(ANDROID_LOG_INFO, "YAMA_SCR", __VA_ARGS__)
|
||
#define LOGE_SH(...) android_log_tag(ANDROID_LOG_ERROR, "YAMA_SCR", __VA_ARGS__)
|
||
|
||
extern uint64_t g_myClientID;
|
||
// 定义在 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);
|
||
extern void DispatchLockScreen();
|
||
// 隐私 overlay(COMMAND_SCREEN_BLANK / COMMAND_SCREEN_BLOCK_INPUT),定义在 main.cpp
|
||
extern void DispatchPrivacyOverlay(bool black, bool block);
|
||
// 画质/帧率协商:读写 ScreenTuning(SharedPreferences),定义在 main.cpp
|
||
extern int GetClientQualityLevel(); // 上报用,读不到时回落 QUALITY_GOOD
|
||
extern int GetClientMaxFps(); // 上报用,读不到时回落 20
|
||
extern void DispatchQualityLevel(int level, bool persist);
|
||
extern void DispatchMaxFps(int fps);
|
||
extern void DispatchQualityProfilesCsv(const char* csv);
|
||
|
||
// Linux/macOS 共用的 BITMAPINFOHEADER 布局(与 Windows 完全一致)
|
||
#pragma pack(push, 1)
|
||
struct BmpInfoHeader {
|
||
uint32_t biSize;
|
||
int32_t biWidth;
|
||
int32_t biHeight;
|
||
uint16_t biPlanes;
|
||
uint16_t biBitCount;
|
||
uint32_t biCompression;
|
||
uint32_t biSizeImage;
|
||
int32_t biXPelsPerMeter;
|
||
int32_t biYPelsPerMeter;
|
||
uint32_t biClrUsed;
|
||
uint32_t biClrImportant;
|
||
};
|
||
#pragma pack(pop)
|
||
|
||
class AndroidScreenHandler : public IOCPManager {
|
||
public:
|
||
AndroidScreenHandler(IOCPClient* client, int width, int height)
|
||
: m_client(client), m_width(width), m_height(height),
|
||
m_started(false), m_running(true), m_firstSent(false)
|
||
{
|
||
memset(&m_bmpHdr, 0, sizeof(m_bmpHdr));
|
||
m_bmpHdr.biSize = sizeof(BmpInfoHeader);
|
||
m_bmpHdr.biWidth = width;
|
||
m_bmpHdr.biHeight = height;
|
||
m_bmpHdr.biPlanes = 1;
|
||
m_bmpHdr.biBitCount = 32;
|
||
m_bmpHdr.biCompression = 0;
|
||
m_bmpHdr.biSizeImage = (uint32_t)(width * height * 4);
|
||
// 1 = top-down H264(Android MediaCodec 标准编码顺序);
|
||
// 服务端据此用负步长写 DIB,抵消 GDI bottom-up 翻转
|
||
m_bmpHdr.biClrImportant = 1;
|
||
|
||
m_sendThread = std::thread(&AndroidScreenHandler::SendLoop, this);
|
||
}
|
||
|
||
~AndroidScreenHandler() {
|
||
// 屏幕子连接断了 overlay 就没人能解除:全屏黑色/不可触摸窗口会把本机用户锁在外面,
|
||
// 必须在 handler 销毁时兜底撤掉(服务端侧也有强制解锁 + 关闭会话的路径,但断网时
|
||
// 服务端已经发不出任何报文)。
|
||
if (m_black.load() || m_block.load()) {
|
||
LOGE_SH("screen conn ended with overlay on (black=%d block=%d); clearing",
|
||
(int)m_black.load(), (int)m_block.load());
|
||
DispatchPrivacyOverlay(false, false);
|
||
}
|
||
m_running = false;
|
||
m_cond.notify_all();
|
||
if (m_sendThread.joinable())
|
||
m_sendThread.join();
|
||
}
|
||
|
||
// 子连接建立后立即调用,告知服务端屏幕尺寸和编码格式
|
||
void SendBitmapInfo() {
|
||
const uint32_t total = 1 + sizeof(BmpInfoHeader) + 2 * sizeof(uint64_t) + sizeof(ScreenSettings);
|
||
std::vector<uint8_t> buf(total, 0);
|
||
|
||
buf[0] = TOKEN_BITMAPINFO;
|
||
memcpy(&buf[1], &m_bmpHdr, sizeof(BmpInfoHeader));
|
||
|
||
uint64_t clientID = g_myClientID;
|
||
uint64_t zero = 0;
|
||
size_t off = 1 + sizeof(BmpInfoHeader);
|
||
memcpy(&buf[off], &clientID, 8);
|
||
memcpy(&buf[off + 8], &zero, 8);
|
||
|
||
ScreenSettings ss = {};
|
||
ss.MaxFPS = GetClientMaxFps();
|
||
ss.ScreenWidth = m_width;
|
||
ss.ScreenHeight = m_height;
|
||
// 上报主控端上次为本机选择的档位(含 QUALITY_ADAPTIVE)。写死成 Good 会让服务端
|
||
// 认为这是「固定档位会话」,m_AdaptiveQuality.enabled 永远为 false——自适应质量
|
||
// 在 Android 主机上根本不会启动。具体编码参数由 ScreenTuning 在 Kotlin 侧应用。
|
||
ss.QualityLevel = GetClientQualityLevel();
|
||
ss.ScreenType = USING_VIRTUAL; // 虚拟显示
|
||
memcpy(&buf[off + 16], &ss, sizeof(ss));
|
||
|
||
m_client->Send2Server((char*)buf.data(), total);
|
||
LOGI_SH("SendBitmapInfo %dx%d clientID=%" PRIu64, m_width, m_height, clientID);
|
||
|
||
// H.264 是推送模式,不需要等 COMMAND_NEXT 才开始发帧。
|
||
// 服务端在 auth 通过瞬间发 COMMAND_NEXT,此时 setManagerCallBack 尚未注册,
|
||
// 消息被 WorkThread 丢弃,m_started 永远 false 导致帧全部卡在队列里。
|
||
m_started = true;
|
||
m_cond.notify_all();
|
||
}
|
||
|
||
// 由 JNI 线程调用,投递 MediaCodec 输出的 NALU
|
||
void OnFrameData(const uint8_t* data, uint32_t size, bool isKeyframe) {
|
||
if (!m_running || size == 0) return;
|
||
{
|
||
std::lock_guard<std::mutex> lk(m_mutex);
|
||
while (m_queue.size() >= 6) m_queue.pop();
|
||
m_queue.push({std::vector<uint8_t>(data, data + size), isKeyframe});
|
||
}
|
||
m_cond.notify_one();
|
||
}
|
||
|
||
virtual VOID OnReceive(PBYTE data, ULONG size) override {
|
||
if (!size) return;
|
||
switch (data[0]) {
|
||
case COMMAND_NEXT:
|
||
// 推送模式下已在 SendBitmapInfo 里开始推流;此处保留兼容,无副作用。
|
||
LOGI_SH("COMMAND_NEXT received");
|
||
m_started = true;
|
||
m_cond.notify_all();
|
||
break;
|
||
case CMD_QUALITY_LEVEL: {
|
||
// [cmd][level:int8][persist:1]。level 有符号(-2 关闭 / -1 自适应 / 0-5 具体档),
|
||
// persist=1 表示这是主控端选定的档位、要落盘(老主控端的负载只有 4 字节)。
|
||
if (size >= 2) {
|
||
const int level = (int)(int8_t)data[1];
|
||
const bool persist = size >= 3 && data[2] != 0;
|
||
DispatchQualityLevel(level, persist);
|
||
}
|
||
break;
|
||
}
|
||
case CMD_FPS:
|
||
// [cmd][fps:1],255 = 不限帧。帧率只能写进 MediaCodec 的 KEY_FRAME_RATE
|
||
// (码控提示),surface 编码器没有运行时限帧开关,所以下次开抓才生效。
|
||
if (size >= 2) DispatchMaxFps((int)(uint8_t)data[1]);
|
||
break;
|
||
case CMD_QUALITY_PROFILES: {
|
||
// [cmd][QualityProfile × QUALITY_COUNT](每档 16 字节)。存下来供开抓与
|
||
// 档位切换时按主控端自定义的码率表取参数(主控端权威,见 ScreenSpyDlg)。
|
||
const size_t need = 1 + sizeof(QualityProfile) * QUALITY_COUNT;
|
||
if ((size_t)size < need) {
|
||
LOGE_SH("QUALITY_PROFILES short: %u < %u", (unsigned)size, (unsigned)need);
|
||
break;
|
||
}
|
||
std::string csv;
|
||
for (int i = 0; i < QUALITY_COUNT; i++) {
|
||
QualityProfile p;
|
||
memcpy(&p, data + 1 + i * sizeof(QualityProfile), sizeof(p));
|
||
if (i) csv += ';';
|
||
csv += std::to_string(p.maxFPS) + ',' + std::to_string(p.maxWidth) + ',' +
|
||
std::to_string(p.algorithm) + ',' + std::to_string(p.bitRate);
|
||
}
|
||
DispatchQualityProfilesCsv(csv.c_str());
|
||
break;
|
||
}
|
||
case CMD_SCREEN_TUNING: {
|
||
// [cmd][flags:4][version:1]。Android 抓屏是 MediaProjection + MediaCodec(H264),
|
||
// 四个开关(x264 VBV / GDI 去延时 / 发送节流 / 自适应判据)都没有对应实现,
|
||
// 因此只记日志、不落盘,也不声明 SCREEN_CAP_TUNING_FLAGS。
|
||
uint32_t flags = 0;
|
||
if (size >= 5) memcpy(&flags, data + 1, 4);
|
||
const int ver = size >= 6 ? (int)data[5] : -1;
|
||
LOGI_SH("SCREEN_TUNING flags=0x%X ver=%d (no-op on Android)", flags, ver);
|
||
break;
|
||
}
|
||
case CMD_SCREEN_SIZE:
|
||
// [cmd][strategy][maxWidth:int]。自适应质量要求缩放编码宽度;Android 源是
|
||
// 整屏抓取、尺寸在开抓时固定(改尺寸需重建 MediaCodec),故忽略。
|
||
// 服务端会按「客户端可能重启」先置分辨率切换标记,1 秒后超时自愈
|
||
// (CheckResolutionChangeTimeout:刷新解码器 + 请求 IDR),表现为切档后
|
||
// 画面停约 1 秒。回发 TOKEN_BITMAPINFO 能立刻清标记,但会连带 PrepareDrawing、
|
||
// 通知 web 端重建解码器,比 1 秒停顿更扰动,因此不这么做。
|
||
LOGI_SH("SCREEN_SIZE ignored on Android (%u bytes)", (unsigned)size);
|
||
break;
|
||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||
// 服务端写剪贴板: [cmd:1][GBK text:N](与 Windows CF_TEXT 同编码;人类剪贴板
|
||
// 同步会带 '\0' 结尾,MCP 路径不带,Kotlin 侧统一去掉尾随 NUL)
|
||
if (size > 1) DispatchClipboardText(data + 1, (size_t)size - 1);
|
||
break;
|
||
case COMMAND_SCREEN_CTRL_ALT_DEL:
|
||
// Ctrl+Alt+Del 在 Android 无对应键,客户端映射为锁屏(GLOBAL_ACTION_LOCK_SCREEN)
|
||
DispatchLockScreen();
|
||
break;
|
||
case COMMAND_SCREEN_BLOCK_INPUT:
|
||
// [cmd][0|1]:1=吃掉本机触摸(透明 overlay),0=解除。
|
||
// 与 Windows 的 BlockInput 语义对齐:服务端注入的手势照常穿透(Kotlin 侧在
|
||
// 手势在飞时临时置 FLAG_NOT_TOUCHABLE,等价于 Windows 的 BlockInput(false) 包裹)。
|
||
if (size >= 2) ApplyOverlay(m_black.load(), data[1] != 0);
|
||
break;
|
||
case COMMAND_SCREEN_BLANK:
|
||
// [cmd][0|1]:1=全屏黑,0=恢复。注意 Android 没有「窗口不参与抓屏」的等价物
|
||
// (Windows 是 WDA_EXCLUDEFROMCAPTURE),黑色 overlay 会被 MediaProjection
|
||
// 一起抓走,主控端看到的画面也会变黑——这是给本机旁观者看的隐私屏,不是隐身。
|
||
if (size >= 2) ApplyOverlay(data[1] != 0, m_block.load());
|
||
break;
|
||
case COMMAND_SCREEN_CONTROL: {
|
||
// 服务端通过子连接下发鼠标/键盘控制包(MSG64 固定 48 字节)
|
||
// 坐标从 lParam(offset 24)读取,与 Windows/Linux/macOS 客户端一致:
|
||
// lParam = MAKELPARAM(enc_x, enc_y),低16位=x,高16位=y。
|
||
// 不读 pt.x/pt.y (offset 40/44):64-bit MSG 的 pt 在 offset 36,
|
||
// 与 MSG64 offset 40 不同,直接读会得到错误坐标。
|
||
if ((ULONG)size < 1 + 48u) break;
|
||
const uint8_t* p = data + 1;
|
||
uint64_t msgVal = 0, wParam = 0, lParam = 0;
|
||
memcpy(&msgVal, p + 8, 8);
|
||
memcpy(&wParam, p + 16, 8);
|
||
memcpy(&lParam, p + 24, 8);
|
||
int32_t ptX = (int32_t)(int16_t)(lParam & 0xFFFF);
|
||
int32_t ptY = (int32_t)(int16_t)((lParam >> 16) & 0xFFFF);
|
||
DispatchControlEvent((uint32_t)msgVal, wParam, ptX, ptY);
|
||
break;
|
||
}
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
|
||
private:
|
||
// 服务端下发的是「绝对状态」(black/block 各一个 bool),这里只记客户端当前状态,
|
||
// 用于两条收尾路径:另一条命令到来时保持它不变、子连接断开时整体撤掉。
|
||
void ApplyOverlay(bool black, bool block) {
|
||
m_black.store(black);
|
||
m_block.store(block);
|
||
LOGI_SH("privacy overlay: black=%d block=%d", (int)black, (int)block);
|
||
DispatchPrivacyOverlay(black, block);
|
||
}
|
||
|
||
struct Frame { std::vector<uint8_t> data; bool isKeyframe; };
|
||
|
||
IOCPClient* m_client;
|
||
int m_width, m_height;
|
||
std::atomic<bool> m_started;
|
||
std::atomic<bool> m_running;
|
||
std::atomic<bool> m_firstSent;
|
||
std::atomic<bool> m_skipLogged{false};
|
||
std::atomic<bool> m_black{false}; // 隐私 overlay:全屏黑(COMMAND_SCREEN_BLANK)
|
||
std::atomic<bool> m_block{false}; // 隐私 overlay:吃掉本机触摸(COMMAND_SCREEN_BLOCK_INPUT)
|
||
|
||
BmpInfoHeader m_bmpHdr;
|
||
|
||
std::queue<Frame> m_queue;
|
||
std::mutex m_mutex;
|
||
std::condition_variable m_cond;
|
||
std::thread m_sendThread;
|
||
|
||
void SendLoop() {
|
||
while (m_running) {
|
||
std::unique_lock<std::mutex> lk(m_mutex);
|
||
m_cond.wait(lk, [&]{ return (!m_queue.empty() && m_started) || !m_running; });
|
||
if (!m_running) break;
|
||
|
||
Frame f = std::move(m_queue.front());
|
||
m_queue.pop();
|
||
lk.unlock();
|
||
|
||
// 第一帧必须是关键帧
|
||
if (!m_firstSent && !f.isKeyframe) {
|
||
if (!m_skipLogged.exchange(true))
|
||
LOGI_SH("SendLoop: waiting for first IDR, skipping P-frames");
|
||
continue;
|
||
}
|
||
|
||
if (!m_firstSent)
|
||
LOGI_SH("SendH264 first IDR size=%u", (uint32_t)f.data.size());
|
||
SendH264(f.data.data(), (uint32_t)f.data.size());
|
||
m_firstSent = true;
|
||
}
|
||
}
|
||
|
||
// 格式: [TOKEN_NEXTSCREEN:1][ALGORITHM_H264:1][cursorX:4][cursorY:4][cursorType:1][NALU:N]
|
||
void SendH264(const uint8_t* nalu, uint32_t naluSize) {
|
||
const uint32_t hdrSize = 1 + 1 + 4 + 4 + 1;
|
||
std::vector<uint8_t> pkt(hdrSize + naluSize);
|
||
|
||
pkt[0] = TOKEN_NEXTSCREEN;
|
||
pkt[1] = ALGORITHM_H264;
|
||
// cursor: (0,0), type: IDC_ARROW=1
|
||
memset(&pkt[2], 0, 8);
|
||
pkt[10] = 1;
|
||
memcpy(&pkt[hdrSize], nalu, naluSize);
|
||
|
||
m_client->Send2Server((char*)pkt.data(), pkt.size());
|
||
}
|
||
};
|