Merge pull request #656 from UjhhgtgTeams/dev

Set up Linux Github Actions Build & Add Linux Build Instructions & Update Readme
This commit is contained in:
Barry 2022-09-12 10:15:37 +08:00 committed by GitHub
commit 5a20373c88
20 changed files with 514 additions and 351 deletions

View file

@ -1,5 +1,4 @@
name: Ubuntu
# Qt官方没有linux平台的x86包
on:
push:
paths:
@ -19,7 +18,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-22.04]
qt-ver: [5.15.1]
qt-ver: [5.15.2]
qt-arch-install: [gcc_64]
gcc-arch: [x64]
env:
@ -27,27 +26,56 @@ jobs:
qt-install-path: ${{ github.workspace }}/${{ matrix.qt-ver }}
plantform-des: ubuntu
steps:
- name: Cache Qt
id: cache-qt
uses: actions/cache@v1
with:
path: ${{ env.qt-install-path }}/${{ matrix.qt-arch-install }}
key: ${{ runner.os }}/${{ matrix.qt-ver }}/${{ matrix.qt-arch-install }}
- name: Install Qt
uses: jurplel/install-qt-action@v2.13.0
with:
version: ${{ matrix.qt-ver }}
cached: ${{ steps.cache-qt.outputs.cache-hit }}
- name: Ubuntu install GL library
- name: Cache Qt
id: cache-qt
uses: actions/cache@v3.0.6
with:
path: ${{ env.qt-install-path }}/${{ matrix.qt-arch-install }}
key: ${{ runner.os }}/${{ matrix.qt-ver }}/${{ matrix.qt-arch-install }}
- name: Install GL library
run: sudo apt-get install -y libglew-dev libglfw3-dev
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: 'true'
ssh-key: ${{ secrets.BOT_SSH_KEY }}
- name: Build Ubuntu
- name: Build RelWithDebInfo
env:
ENV_QT_PATH: ${{ env.qt-install-path }}
run: |
python ci/generate-version.py
ci/linux/build_for_ubuntu.sh RelWithDebInfo
ci/linux/build_for_linux.sh "RelWithDebInfo"
- name: Upload RelWithDebInfo
uses: actions/upload-artifact@v3.1.0
with:
name: QtScrcpy-${{ matrix.os }}-${{ matrix.qt-arch-install }}-RelWithDebInfo
path: output/x64/RelWithDebInfo/*
- name: Build Release
env:
ENV_QT_PATH: ${{ env.qt-install-path }}
run: |
ci/linux/build_for_linux.sh "Release"
- name: Upload Release
uses: actions/upload-artifact@v3.1.0
with:
name: QtScrcpy-${{ matrix.os }}-${{ matrix.qt-arch-install }}-Release
path: output/x64/Release/*
- name: Install the zip utility
run: |
sudo apt install zip -y
- name: Zip the Artifacts
run: |
zip -r QtScrcpy-${{ matrix.os }}-${{ matrix.qt-arch-install }}.zip output/x64/Release
- name: Upload to Releases
if: startsWith(github.ref, 'refs/tags/')
uses: svenstaro/upload-release-action@2.3.0
with:
file: QtScrcpy-${{ matrix.os }}-${{ matrix.qt-arch-install }}.zip
asset_name: QtScrcpy-${{ matrix.os }}-${{ matrix.qt-arch-install }}.zip
repo_token: ${{ secrets.GITHUB_TOKEN }}
tag: ${{ github.ref }}
overwrite: true

101
README.md
View file

@ -8,20 +8,20 @@
![license](https://img.shields.io/badge/license-Apache2.0-blue.svg)
![release](https://img.shields.io/github/v/release/barry-ran/QtScrcpy.svg)
[中文介绍](README_zh.md)
[中文用户?点我查看中文介绍](README_zh.md)
QtScrcpy connects to Android devices via USB (or via TCP/IP) for display and control. It does NOT require root privileges.
QtScrcpy supports displaying and controlling Android devices via USB or over network. It does NOT require root privileges.
It supports three major platforms: GNU/Linux, Windows and macOS.
It focuses on:
- **lightness** (native, displays only the device screen)
- **performance** (30~60fps)
- **lightness** (displays only the device screen)
- **performance** (30~60 fps)
- **quality** (1920×1080 or above)
- **low latency** ([35~70ms][lowlatency])
- **low startup time** (~1 second to display the first image)
- **non-intrusiveness** (nothing is left installed on the device)
- **low startup time** (only about 1 second to display the first frame)
- **non-intrusiveness** (nothing will be installed on the device)
[lowlatency]: https://github.com/Genymobile/scrcpy/pull/646
@ -31,37 +31,37 @@ It focuses on:
![linux](screenshot/linux-en.png)
## Customized key mapping
You can write your script to map keyboard and mouse actions to touches and clicks of the mobile phone according to your needs. [Here](docs/KeyMapDes.md) are the rules.
## Mapping Keys
You can write your script to map keyboard and mouse actions to touches and clicks of the mobile phone according to your needs. [Here](docs/KeyMapDes.md) are the script writing rules.
A script for "PUBG mobile" and TikTok mapping is provided by default. Once enabled, you can play the game with your keyboard and mouse as the PC version. or you can use up/down/left/right direction keys to simulate up/down/left/right sliding. You can also write your mapping files for other games according to [the writing rules](docs/KeyMapDes.md). The default key mapping is as follows:
Script for TikTok and some other games are provided by default. Once enabled, you can play the game with your keyboard and mouse. The default key mapping for PUBG Mobile is as follows:
![game](screenshot/game.jpg)
[Here is a video demonstration of playing "PUBG mobile"](http://mp.weixin.qq.com/mp/video?__biz=MzU1NTg5MjYyNw==&mid=100000015&sn=3e301fdc5a364bd16d6207fa674bc8b3&vid=wxv_968792362971430913&idx=1&vidsn=eec329cc13c3e24c187dc9b4d5eb8760&fromid=1&scene=20&xtrack=1&clicktime=1567346543&sessionid=1567346375&subscene=92&ascene=0&fasttmpl_type=0&fasttmpl_fullversion=4730859-zh_CN-zip&fasttmpl_flag=0&realreporttime=1567346543910#wechat_redirect)
[Here is a video demonstration playing PUBG Mobile.](http://mp.weixin.qq.com/mp/video?__biz=MzU1NTg5MjYyNw==&mid=100000015&sn=3e301fdc5a364bd16d6207fa674bc8b3&vid=wxv_968792362971430913)
Here is the instruction for adding new customized mapping files.
Instruction for adding new customized mapping files.
- Write a customized script and put it in the `keymap` directory
- Click `refresh script` to check whether it can be found
- Click `refresh script` to show it
- Select your script
- Connect your phone, start service and click `apply`
- Press `~` key (left side of the number key 1) to switch to the custom mapping mode (It can be changed in the script as `switchkey`)
- Connect to your phone, start service and click `apply`
- Press `~` key (the SwitchKey in the key map script) to switch to custom mapping mode
- Press the ~ key again to switch back to normal mode
- (For PUBG and similar games) If you want to drive cars with WASD, you need to check the `single rocker mode` in the game setting.
- (For games such as PUBG Mobile) If you want to move vehicles with the STEER_WHEEL keys, you need to set the move mode to `single rocker mode`.
## Group control
You can control all your phones at the same time.
![](docs/image/group-control.gif)
![group-control-demo](docs/image/group-control.gif)
## Thanks
QtScrcpy is based on [Genymobile's](https://github.com/Genymobile) [scrcpy](https://github.com/Genymobile/scrcpy) project. Thanks
QtScrcpy is based on [Genymobile](https://github.com/Genymobile)'s [scrcpy](https://github.com/Genymobile/scrcpy) project. Thanks a lot!
The difference between QtScrcpy and the original scrcpy is as follows:
keys|scrcpy|QtScrcpy
key points|scrcpy|QtScrcpy
--|:--:|:--:
ui|sdl|qt
video encode|ffmpeg|ffmpeg
@ -104,22 +104,29 @@ Make sure you have enabled [ADB debugging][enable-adb] on your device(s).
[github-download]: https://github.com/barry-ran/QtScrcpy/releases
### Windows
For Windows, for simplicity, prebuilt archives with all the dependencies (including ADB) are available:
On Windows, for simplicity, prebuilt archives with all the dependencies (including ADB) are available at Releases:
- [`QtScrcpy`][github-download]
or you can [build it by yourself](#Build)
or you can [build it yourself](#Build)
### Mac OS
For Mac OS, for simplicity, prebuilt archives with all the dependencies (including ADB) are available:
On Mac OS, for simplicity, prebuilt archives with all the dependencies (including ADB) are available at Releases:
- [`QtScrcpy`][github-download]
or you can [build it by yourself](#Build)
or you can [build it yourself](#Build)
### Linux
you can [build it by yourself](#Build)(just ubuntu test)
For Arch Linux Users, you can use AUR to install: `yay -Syu qtscrcpy` (may be outdated; maintainer: [yochananmarqos](https://aur.archlinux.org/account/yochananmarqos))
For users in other distros, you can use the prebuilt archives from Releases:
- [`QtScrcpy`][github-download]
or you can get it at [GitHub Actions](https://github.com/UjhhgtgTeams/QtScrcpy/actions/workflows/ubuntu.yml), in branch `dev` and download the latest artifact.
or you can [build it yourself](#Build) (not recommended, get it in Actions if you can)
## Run
Connect to your Android device on your computer, then run the program and click `USB connect` or `WiFi connect`
@ -176,10 +183,9 @@ Note: it is not necessary to keep your Android device connected via USB after yo
It is possible to synchronize clipboards between the computer and the device, in
both directions:
- `Ctrl`+`c` copies the device clipboard to the computer clipboard;
- `Ctrl`+`Shift`+`v` copies the computer clipboard to the device clipboard;
- `Ctrl`+`v` _pastes_ the computer clipboard as a sequence of text events (but
breaks non-ASCII characters).
- `Ctrl + c` copies the device clipboard to the computer clipboard;
- `Ctrl + Shift + v` copies the computer clipboard to the device clipboard;
- `Ctrl + v` _pastes_ the computer clipboard as a sequence of text events (non-ASCII characters does not yet work).
- Group control
- Sync device speaker sound to the computer (based on [sndcpy](https://github.com/rom1v/sndcpy), Android 10+ only)
@ -222,39 +228,44 @@ _³Only on Android >= 7._
[DEVELOP](docs/DEVELOP.md)
Everyone is welcome to maintain this project and contribute your own code, but please follow these requirements:
1. pr please mention the dev branch, not the master branch
2. Please rebase dev before mentioning pr
3. pr please submit on the principle of a small number of times (a small function point is recommended to mention a pr)
4. Please keep the code style consistent with the existing style
1. Please open PRs to the dev branch instead of the master branch
2. Please rebase the original project before opening PRs
3. Please submit PRs on the principle of "small amounts, many times" (one PR for a change is recommended)
4. Please keep the code style consistent with the existing style.
## Why develop QtScrcpy?
There are several reasons listed below according to importance (high to low).
1. In the process of learning Qt, I need a real project to try
2. I have some background skills in audio and video and I am interested in them
1. In the process of learning Qt, I need a real project to try.
2. I have some background skills in audio and video and I am interested in them.
3. I have some Android development skills. But I have used it for a long time. I want to consolidate it.
4. I found scrcpy and decided to re-make it with the new technology stack (C++ + Qt + Opengl + FFmpeg)
4. I found scrcpy and decided to re-make it with the new technology stack (C++ + Qt + Opengl + FFmpeg).
## Build
All the dependencies are provided and it is easy to compile.
### PC client
1. Set up the Qt development environment on the target platform.
Qt version>=5.12 (use MSVC 2019 on Windows)
2. Clone the project (git clone --recursive git@github.com:barry-ran/QtScrcpy.git)
3. Open the project root directory `CMakeLists.txt` with QtCreator
4. Compile and run
### QtScrcpy
#### Non-Arch Linux Users
1. Set up the Qt development environment with the official Qt installer or third-party tools such as [aqt](https://github.com/miurahr/aqtinstall) on the target platform.
Qt version bigger than 5.12 is required. (use MSVC 2019 on Windows)
2. Clone the project with `git clone --recurse-submodules https://barry-ran/QtScrcpy.git`
3. For Windows, open CMakeLists.txt with QtCreator and compile Release
4. For Linux, directly run `./ci/linux/build_for_linux.sh "Release"`
Note: compiled artifacts are located at `output/x64/Release`
### Android (If you do not have special requirements, you can directly use the built-in scrcpy-server.jar)
#### Arch Linux Users
1. Install packages: `base-devel cmake qt5-base qt5-multimedia qt5-x11extras` (`qtcreator` is recommended)
2. Clone the project with `git clone --recurse-submodules https://barry-ran/QtScrcpy.git`
3. Run `./ci/linux/build_for_linux.sh "Release"`
1. Set up an Android development environment on the target platform
### Scrcpy-Server
1. Set up Android development environment on the target platform
2. Open server project in project root with Android Studio
3. The first time you open it, if you do not have the corresponding version of Gradle, you will be prompted to find Gradle, whether to upgrade Gradle or create it. Select Cancel. After canceling, you will be prompted to select the location of the existing Gradle. You can also cancel it (it will download automatically).
4. Edit the code as needed, but of course, you dont need to.
3. The first time you open it, if you do not have the corresponding version of Gradle, you will be prompted to find Gradle, whether to upgrade Gradle or create it. Select Cancel. After cancelling, you will be prompted to select the location of existing Gradle. Cancel it too and it will download automatically.
4. After compiling the apk, rename it to scrcpy-server and replace QtScrcpy/QtScrcpyCore/src/third_party/scrcpy-server.
## Licence
Since it is based on scrcpy, respect its Licence
Since it is based on scrcpy, it uses the same license as scrcpy
Copyright (C) 2025 Rankun

View file

@ -7,11 +7,11 @@
![license](https://img.shields.io/badge/license-Apache2.0-blue.svg)
![release](https://img.shields.io/github/v/release/barry-ran/QtScrcpy.svg)
[English introduction](README.md)
[Speaks English? Click me for English introduction.](README.md)
QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和控制。不需要root权限。
QtScrcpy 可以通过 USB / 网络连接Android设备并进行显示和控制。无需root权限。
同时支持GNU/LinuxWindows和MacOS三大主流桌面平台
同时支持 GNU/Linux Windows 和 MacOS 三大主流桌面平台。
它专注于:
@ -19,7 +19,7 @@ QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和
- **性能** (30~60fps)
- **质量** (1920×1080以上)
- **低延迟** ([35~70ms][低延迟])
- **快速启动** (1s内就可以看到第一帧图像)
- **快速启动** (1s 内就可以看到第一帧图像)
- **非侵入性** (不在设备上安装任何软件)
[低延迟]: https://github.com/Genymobile/scrcpy/pull/646
@ -31,7 +31,7 @@ QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和
![linux](screenshot/linux-zh.png)
## 自定义按键映射
可以根据需要,自己编写脚本将PC键盘按键映射为手机的触摸点击,编写规则在[这里](docs/KeyMapDes_zh.md)。
可以根据需要,自己编写脚本将键盘按键映射为手机的触摸点击,编写规则在[这里](docs/KeyMapDes_zh.md)。
默认自带了针对和平精英手游和抖音进行键鼠映射的映射脚本,开启平精英手游后可以用键鼠像玩端游一样玩和平精英手游,开启抖音映射以后可以使用上下左右方向键模拟上下左右滑动,你也可以按照[编写规则](docs/KeyMapDes_zh.md)编写其他游戏的映射文件,默认按键映射如下:
@ -40,13 +40,13 @@ QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和
[这里有玩和平精英的视频演示](http://mp.weixin.qq.com/mp/video?__biz=MzU1NTg5MjYyNw==&mid=100000015&sn=3e301fdc5a364bd16d6207fa674bc8b3&vid=wxv_968792362971430913&idx=1&vidsn=eec329cc13c3e24c187dc9b4d5eb8760&fromid=1&scene=20&xtrack=1&clicktime=1567346543&sessionid=1567346375&subscene=92&ascene=0&fasttmpl_type=0&fasttmpl_fullversion=4730859-zh_CN-zip&fasttmpl_flag=0&realreporttime=1567346543910#wechat_redirect)
自定义按键映射操作方法如下:
- 编写自定义脚本放入keymap目录
- 编写自定义脚本放入 keymap 目录
- 点击刷新脚本,确保脚本可以被检测到
- 选择需要的脚本
- 连接手机并启动服务之后,点击应用脚本
- 按~键数字键1左边切换为自定义映射模式即可体验具体按什么键要看你按键脚本定义的switchKey
- 按`~`(即脚本中定义的 SwitchKey键切换为自定义映射模式即可启用
- 再次按~键切换为正常控制模式
- 要想wasd控制开车记得在载具设置中设置为单摇杆模式
- (对于和平精英等游戏)若想使用方向盘控制载具,记得在载具设置中设置为单摇杆模式
## 群控
你可以同时控制所有的手机
@ -55,18 +55,20 @@ QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和
## 感谢
基于[Genymobile](https://github.com/Genymobile)的[scrcpy](https://github.com/Genymobile/scrcpy)项目进行复刻,重构,非常感谢。QtScrcpy和原版scrcpy区别如下
基于[Genymobile](https://github.com/Genymobile)的[scrcpy](https://github.com/Genymobile/scrcpy)项目进行复刻,重构,非常感谢。
## 比较
QtScrcpy 和 Scrcpy 区别如下:
关键点|scrcpy|QtScrcpy
--|:--:|:--:
界面|sdl|qt
视频解码|ffmpeg|ffmpeg
视频渲染|sdl|opengl
跨平台基础设施|自己封装|Qt提供
跨平台基础设施|自己封装|Qt
编程语言|C|C++
编程方式|同步|异步
按键映射|不支持自定义|支持自定义按键映射
编译方式|meson+gradle|qmake or CMake
编译方式|Meson+Gradle|CMake
- 使用Qt可以非常容易的定制自己的界面
- 基于Qt的信号槽机制的异步编程提高性能
@ -76,111 +78,116 @@ QtScrcpy可以通过USB(或通过TCP/IP)连接Android设备并进行显示和
## 学习它
如果你对它感兴趣,想学习它的实现原理而又感觉无从下手,可以选择购买我录制的视频课程,
里面详细介绍了整个软件的开发架构以及开发流程带你从无到有的开发QtScrcpy
里面详细介绍了整个软件的开发架构以及开发流程,带你从无到有的开发 QtScrcpy
课程介绍:[https://blog.csdn.net/rankun1/article/details/87970523](https://blog.csdn.net/rankun1/article/details/87970523)
或者你也可以加入我的QtScrcpy QQ群和志同道合的朋友一块互相交流技术
或者你也可以加入我的 QtScrcpy QQ 群,和志同道合的朋友一块互相交流技术:
QQ群号901736468
## 要求
Android部分至少需要API 21Android 5.0)。
Android 部分至少需要 API 21Android 5.0)。
您要确保在Android设备上[启用adb调试][enable-adb]。
您要确保在 Android 设备上[启用adb调试][enable-adb]。
[enable-adb]: https://developer.android.com/studio/command-line/adb.html#Enabling
## 下载这个软件
## 下载
[gitee-download]: https://gitee.com/Barryda/QtScrcpy/releases
[github-download]: https://github.com/barry-ran/QtScrcpy/releases
### Windows
Windows平台你可以直接使用我编译好的可执行程序:
Windows 平台,你可以直接使用我编译好的可执行程序:
- [国内下载][gitee-download]
- [国外下载][github-download]
你也可以[自己编译](##如何编译)
你也可以[自己编译](##编译)
### Mac OS
Mac OS平台你可以直接使用我编译好的可执行程序:
Mac OS 平台,你可以直接使用我编译好的可执行程序:
- [国内下载][gitee-download]
- [国外下载][github-download]
你也可以[自己编译](##如何编译)
你也可以[自己编译](##编译)
### Linux
目前只提供了windows和mac平台的可执行程序如果需要linux平台的可执行程序
对于 Arch Linux 用户,可以使用 AUR 安装:`yay -Syu qtscrcpy`(可能版本并非最新;维护者:[yochananmarqos](https://aur.archlinux.org/account/yochananmarqos)
您通常需要[自己编译](##如何编译)。别担心,这并不难。
其他发行版的用户可以直接使用我编译好的可执行程序:
目前只在ubuntu上测试过
- [国外下载][github-download]
你也可以从 [GitHub Actions](https://github.com/UjhhgtgTeams/QtScrcpy/actions/workflows/ubuntu.yml) 获取最新的自动编译好的软件
当然,你也可以[自己编译](##编译)(不推荐,需要准备环境)
目前只在 Ubuntu 和 Arch Linux 上测试过编译过程
## 运行
在你的电脑上接入Android设备然后运行程序点击`一键USB连接`或者`一键WIFI连接`
在你的电脑上接入Android设备然后运行程序点击 `一键USB连接` 或者 `一键WIFI连接`
### 无线连接步骤(保证手机和电脑在同一个局域网):
1. 安卓手机端在开发者选项中打开usb调试
2. 通过usb连接安卓手机到电脑
3. 点击刷新设备,会看到有设备号更新出来
4. 点击获取设备IP
5. 点击启动adbd
6. 无线连接
7. 再次点击刷新设备发现多出了一个IP地址开头的设备选择这个设备
8. 启动服务
### 无线连接步骤
1. 将手机和电脑连接到同一局域网
2. 安卓手机端在开发者选项中打开 USB 调试
3. 通过 USB 连接安卓手机到电脑
4. 点击刷新设备,会看到有设备号更新出来
5. 点击获取设备 IP
6. 点击启动 adbd
7. 无线连接
8. 再次点击刷新设备,发现多出了一个 IP 地址开头的设备,选择这个设备
9. 启动服务
备注:启动adbd以后不用再连着usb线了以后连接断开都不再需要除非安卓adbd停了需要重新启动
备注:启动 adbd 以后无需继续连接 USB 线,以后连接断开都不再需要,除非 adbd 停止运行
## 界面按钮介绍:
## 界面解释
- 启动配置:启动服务前的功能参数设置
分别可以设置本地录制视频的比特率、分辨率、录制格式、录像保存路径等。
- 仅后台录制:启动服务不现实界面只是录制Android设备屏幕
- 窗口置顶Android设备视频窗口置顶显示
- 自动息屏启动服务以后自动关闭Android设备屏幕节省电量
- 使用reverse服务启动模式出现服务启动失败报错more than one device可以去掉这个勾选尝试连接
- 仅后台录制:启动服务不显示界面,只录制 Android 设备屏幕
- 窗口置顶Android 设备显示窗口置顶
- 自动息屏:启动服务以后,自动关闭 Android 设备屏幕节省电量
- 使用 Reverse服务启动模式出现服务启动失败报错 "more than one device" 可以去掉这个勾选尝试连接
- 刷新设备列表:刷新当前连接的设备
- 启动服务连接到Android设备
- 停止服务断开与Android设备的连接
- 停止所有服务断开所有已连接的Android设备
- 获取设备ip获取到Android设备的ip地址更新到“无线”区域中,方便进行无线连接
- 启动adbd启动Android设备的adbd服务无线连接之前必须要启动
- 无线连接使用无线方式连接Android设备
- 无线断开断开无线方式连接的Android设备
- adb命令行:方便执行自定义adb命令目前不支持阻塞命令例如shell
- 启动服务:连接到 Android 设备
- 停止服务:断开与 Android 设备的连接
- 停止所有服务:断开所有已连接的 Android 设备
- 获取设备ip获取到 Android 设备的 IP 地址,更新到无线区域中,方便进行无线连接
- 启动adbd启动 Android 设备的 adbd 服务,无线连接之前,必须要启动
- 无线连接:使用无线方式连接 Android 设备
- 无线断开:断开无线方式连接的 Android 设备
- 命令行:执行自定义 adb 命令目前不支持阻塞命令例如shell
## 主要功能
- 实时显示Android设备屏幕
## 功能
- 实时显示 Android 设备屏幕
- 实时键鼠控制Android设备
- 屏幕录制
- 截图为png
- 截图
- 无线连接
- 支持多台设备连接
- 多设备连接与群控
- 全屏显示
- 窗口置顶
- 安装apk拖拽apk到视频窗口即可安装
- 传输文件拖拽文件到视频窗口即可发送文件到Android设备
- 后台录制:只录制,不显示界面
- 复制粘贴
在计算机和设备之间双向同步剪贴板:
- `Ctrl` + `c`将设备剪贴板复制到计算机剪贴板;
- `Ctrl` + `Shift` + `v`将计算机剪贴板复制到设备剪贴板;
- `Ctrl` +`v` 将计算机剪贴板作为一系列文本事件发送到设备不支持非ASCII字符
- 群控
- 同步设备扬声器声音到电脑(基于[sndcpy](https://github.com/rom1v/sndcpy)仅支持安卓10+
- 安装 apk拖拽apk到显示窗口即可安装
- 传输文件:拖拽文件到显示窗口即可发送文件到 Android 设备
- 后台录制:只录制屏幕,不显示界面
- 剪贴板同步:
在计算机和设备之间同步剪贴板:
- `Ctrl + c`将设备剪贴板复制到计算机剪贴板;
- `Ctrl + Shift + v`将计算机剪贴板复制到设备剪贴板;
- `Ctrl + v` 将计算机剪贴板作为一系列文本事件发送到设备不支持非ASCII字符
- 同步设备扬声器声音到电脑(基于[sndcpy](https://github.com/rom1v/sndcpy)仅支持安卓10级以上目前不推荐使用可使用蓝牙连接替代
## 快捷键
@ -216,41 +223,49 @@ Mac OS平台你可以直接使用我编译好的可执行程序:
[常见问题说明](docs/FAQ.md)
## 开发者
[开发相关](docs/DEVELOP.md)
[开发相关](docs/DEVELOP.md)
欢迎大家一起维护这个项目,贡献自己的代码,不过请遵循下几点要求:
1. pr请提到dev分支不要提到master分支
2. 提pr之前请先rebase dev
3. pr请以少量多次的原则提交建议一个小的功能点提一个pr
4. 代码风格请保持和有风格一致
欢迎大家一起维护这个项目,贡献自己的代码,不过请遵循下几点要求:
1. PR 请推向 dev 分支,不要推向 master 分支
2. 提交 PR 之前请先变基原项目
3. PR 请以少量多次的原则提交(即一个功能点提交一个 PR
4. 代码风格请保持和有风格一致
## 为什么开发QtScrcpy
## 为什么开发 QtScrcpy
综合起来有以下几个原因,比重从大到小排列:
1. 学习Qt的过程中需要一个项目实战一下
2. 本身具有音视频相关技能,对音视频很感兴趣
3. 本身具有Android开发技能好久没用有点生疏需要巩固一下
4. 发现了scrcpy决定用新的技术栈C++ + Qt + Opengl + ffmpeg复刻一下
3. 本身具有 Android 开发技能,好久没用有点生疏,需要巩固一下
4. 发现了 Scrcpy决定用新的技术栈C++ + Qt + Opengl + FFmpeg进行复刻
## 如何编译
## 编译
尽量提供了所有依赖资源,方便傻瓜式编译。
### PC端
1. 在目标平台上搭建Qt开发环境
Qt版本>=5.12在Windows上使用MSVC 2019
2. 克隆该项目git clone --recursive git@github.com:barry-ran/QtScrcpy.git
3. 使用QtCreator打开项目根目录`CMakeLists.txt`
4. 编译,运行
### QtScrcpy
#### 非 Arch Linux
1. 使用官方 Qt Installer 或非官方工具(如 [aqt](https://github.com/miurahr/aqtinstall)在目标平台上搭建Qt开发环境。
需要 5.12 以上版本 Qt在 Windows 上使用 MSVC 2019
2. 克隆该项目:`git clone --recurse-submodules https://github.com/barry-ran/QtScrcpy.git`
3. Windows 使用 QtCreator 打开项目下 CMakeLists.txt 并编译 Release
4. Linux 用终端执行 `./ci/linux/build_for_linux.sh "Release"`
注:编译结果位于 `output/x64/Release`
### Android端 没有修改需求的话直接使用自带的scrcpy-server即可
1. 目标平台上搭建Android开发环境
2. 使用Android Studio打开项目根目录中的server项目
3. 第一次打开如果你没有对应版本的gradle会提示找不到gradle是否升级gradle并创建选择取消取消后会弹出选择已有gradle的位置同样取消即可会自动下载
4. 按需编辑代码即可,当然也可以不编辑
4. 编译出apk以后改名为scrcpy-server并替换third_party/scrcpy-server即可
#### Arch Linux
1. 安装以下包:`qt5-base qt5-multimedia qt5-x11extras`(推荐安装 `qtcreator`
2. 克隆该项目:`git clone --recurse-submodules https://github.com/barry-ran/QtScrcpy.git`
3. 用终端执行 `./ci/linux/build_for_linux.sh "Release"`
注:编译结果位于 `output/x64/Release`
### Scrcpy-Server
1. 目标平台上搭建 Android 开发环境
2. 使用 Android Studio 打开项目根目录中的 server
3. 第一次打开时,如果你没有对应版本的 GradleStudio 会提示找不到 Gradle是否升级 Gradle 并创建,选择取消,取消后会提示选择 Gradle 的位置同样取消即可。Studio 会随后自动下载。
4. 按需编辑代码
5. 编译出 apk 以后改名为 scrcpy-server 并替换 `third_party/scrcpy-server` 即可
## Licence
由于是复刻的scrcpy尊重它的Licence
由于是复刻的 Scrcpy尊重它的 Licence
Copyright (C) 2025 Rankun
@ -268,6 +283,6 @@ Qt版本>=5.12在Windows上使用MSVC 2019
## 关于作者
[BarryCSDN](https://blog.csdn.net/rankun1)
[BarryCSDN](https://blog.csdn.net/rankun1)
一枚普通的程序员工作中主要使用C++进行桌面客户端开发一毕业在山东做过一年多钢铁仿真教育软件后来转战上海先后从事安防在线教育相关领域工作对音视频比较熟悉对音视频领域如语音通话直播教育视频会议等相关解决方案有所了解。同时具有AndroidLinux服务器等开发经验。
一枚普通的程序员,工作中主要使用 C++ 进行桌面客户端开发一毕业在山东做过一年多钢铁仿真教育软件后来转战上海先后从事安防在线教育相关领域工作对音视频比较熟悉对音视频领域如语音通话直播教育视频会议等相关解决方案有所了解。同时具有AndroidLinux服务器等开发经验。

67
ci/linux/build_for_linux.sh Executable file
View file

@ -0,0 +1,67 @@
echo ---------------------------------------------------------------
echo Check \& Set Environment Variables
echo ---------------------------------------------------------------
# Get Qt path
# ENV_QT_PATH example: /home/barry/Qt5.9.6/5.9.6
echo Current ENV_QT_PATH: $ENV_QT_PATH
echo Current directory: $(pwd)
# Set variables
qt_cmake_path=$ENV_QT_PATH/gcc_64/lib/cmake/Qt5
export PATH=$qt_gcc_path/bin:$PATH
# Remember working directory
old_cd=$(pwd)
# Set working dir to the script's path
cd $(dirname "$0")/.../
echo
echo
echo ---------------------------------------------------------------
echo Check Build Parameters
echo ---------------------------------------------------------------
echo Possible build modes: Debug/Release/MinSizeRel/RelWithDebInfo
build_mode="$1"
if [[ $build_mode != "Release" && $build_mode != "Debug" && $build_mode != "MinSizeRel" && $build_mode != "RelWithDebInfo" ]]; then
echo "error: unknown build mode, exiting......"
exit 1
fi
echo Current build mode: $build_mode
echo
echo
echo ---------------------------------------------------------------
echo CMake Build Begins
echo ---------------------------------------------------------------
# Remove output folder
output_path=./output
if [ -d "$output_path" ]; then
rm -rf $output_path
fi
cmake_params="-DCMAKE_PREFIX_PATH=$qt_cmake_path -DCMAKE_BUILD_TYPE=$build_mode"
cmake $cmake_params .
if [ $? -ne 0 ] ;then
echo "error: CMake failed, exiting......"
exit 1
fi
cmake --build . --config "$build_mode" -j8
if [ $? -ne 0 ] ;then
echo "error: CMake build failed, exiting......"
exit 1
fi
echo
echo
echo ---------------------------------------------------------------
echo CMake Build Succeeded
echo ---------------------------------------------------------------
# Resume current directory
cd $old_cd
exit 0

View file

@ -1,85 +0,0 @@
echo
echo
echo ---------------------------------------------------------------
echo check ENV
echo ---------------------------------------------------------------
# 从环境变量获取必要参数
# 例如 /home/barry/Qt5.9.6/5.9.6
echo ENV_QT_PATH $ENV_QT_PATH
qt_cmake_path=$ENV_QT_PATH/gcc_64/lib/cmake/Qt5
# 获取绝对路径,保证其他目录执行此脚本依然正确
{
cd $(dirname "$0")
script_path=$(pwd)
cd -
} &> /dev/null # disable output
# 设置当前目录cd的目录影响接下来执行程序的工作目录
old_cd=$(pwd)
cd $(dirname "$0")
# 启动参数声明
build_mode=RelWithDebInfo
echo
echo
echo ---------------------------------------------------------------
echo check build param[Debug/Release/MinSizeRel/RelWithDebInfo]
echo ---------------------------------------------------------------
# 编译参数检查
build_mode=$(echo $1)
if [[ $build_mode != "Release" && $build_mode != "Debug" && $build_mode != "MinSizeRel" && $build_mode != "RelWithDebInfo" ]]; then
echo "error: unkonow build mode -- $1"
exit 1
fi
# 提示
echo current build mode: $build_mode
# 环境变量设置
#export PATH=$qt_gcc_path/bin:$PATH
echo
echo
echo ---------------------------------------------------------------
echo begin cmake build
echo ---------------------------------------------------------------
# 删除输出目录
output_path=$script_path../../output
if [ -d "$output_path" ]; then
rm -rf $output_path
fi
# 删除临时目录
build_path=$script_path/../build_temp
if [ -d "$build_path" ]; then
rm -rf $build_path
fi
mkdir $build_path
cd $build_path
cmake_params="-DCMAKE_PREFIX_PATH=$qt_cmake_path -DCMAKE_BUILD_TYPE=$build_mode"
cmake $cmake_params ../..
if [ $? -ne 0 ] ;then
echo "cmake failed"
exit 1
fi
cmake --build . --config $build_mode -j8
if [ $? -ne 0 ] ;then
echo "cmake build failed"
exit 1
fi
echo
echo
echo ---------------------------------------------------------------
echo finish!!!
echo ---------------------------------------------------------------
# 恢复当前目录
cd $old_cd
exit 0

View file

@ -6,8 +6,8 @@ android {
applicationId "com.genymobile.scrcpy"
minSdkVersion 21
targetSdkVersion 31
versionCode 12100
versionName "1.21"
versionCode 12400
versionName "1.24"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {

7
server/build_without_gradle.sh Normal file → Executable file
View file

@ -12,10 +12,9 @@
set -e
SCRCPY_DEBUG=false
SCRCPY_VERSION_NAME=1.21
SCRCPY_VERSION_NAME=1.24
PLATFORM_VERSION=31
PLATFORM=${ANDROID_PLATFORM:-$PLATFORM_VERSION}
PLATFORM=${ANDROID_PLATFORM:-31}
BUILD_TOOLS=${ANDROID_BUILD_TOOLS:-31.0.0}
BUILD_DIR="$(realpath ${BUILD_DIR:-build_manual})"
@ -57,7 +56,7 @@ javac -bootclasspath "$ANDROID_JAR" -cp "$CLASSES_DIR" -d "$CLASSES_DIR" \
echo "Dexing..."
cd "$CLASSES_DIR"
if [[ $PLATFORM_VERSION -lt 31 ]]
if [[ $PLATFORM -lt 31 ]]
then
# use dx
"$ANDROID_HOME/build-tools/$BUILD_TOOLS/dx" --dex \

View file

@ -1,28 +0,0 @@
apply plugin: 'checkstyle'
check.dependsOn 'checkstyle'
checkstyle {
toolVersion = '6.19'
}
task checkstyle(type: Checkstyle) {
description = "Check Java style with Checkstyle"
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
source = javaSources()
classpath = files()
ignoreFailures = true
}
def javaSources() {
def files = []
android.sourceSets.each { sourceSet ->
sourceSet.java.each { javaSource ->
javaSource.getSrcDirs().each {
if (it.exists()) {
files.add(it)
}
}
}
}
return files
}

View file

@ -71,12 +71,13 @@ public final class ControlMessage {
return msg;
}
public static ControlMessage createInjectScrollEvent(Position position, int hScroll, int vScroll) {
public static ControlMessage createInjectScrollEvent(Position position, int hScroll, int vScroll, int buttons) {
ControlMessage msg = new ControlMessage();
msg.type = TYPE_INJECT_SCROLL_EVENT;
msg.position = position;
msg.hScroll = hScroll;
msg.vScroll = vScroll;
msg.buttons = buttons;
return msg;
}

View file

@ -10,7 +10,7 @@ public class ControlMessageReader {
static final int INJECT_KEYCODE_PAYLOAD_LENGTH = 13;
static final int INJECT_TOUCH_EVENT_PAYLOAD_LENGTH = 27;
static final int INJECT_SCROLL_EVENT_PAYLOAD_LENGTH = 20;
static final int INJECT_SCROLL_EVENT_PAYLOAD_LENGTH = 24;
static final int BACK_OR_SCREEN_ON_LENGTH = 1;
static final int SET_SCREEN_POWER_MODE_PAYLOAD_LENGTH = 1;
static final int GET_CLIPBOARD_LENGTH = 1;
@ -154,7 +154,8 @@ public class ControlMessageReader {
Position position = readPosition(buffer);
int hScroll = buffer.getInt();
int vScroll = buffer.getInt();
return ControlMessage.createInjectScrollEvent(position, hScroll, vScroll);
int buttons = buffer.getInt();
return ControlMessage.createInjectScrollEvent(position, hScroll, vScroll, buttons);
}
private ControlMessage parseBackOrScreenOnEvent() {

View file

@ -22,6 +22,7 @@ public class Controller {
private final DesktopConnection connection;
private final DeviceMessageSender sender;
private final boolean clipboardAutosync;
private final boolean powerOn;
private final KeyCharacterMap charMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
@ -32,10 +33,11 @@ public class Controller {
private boolean keepPowerModeOff;
public Controller(Device device, DesktopConnection connection, boolean clipboardAutosync) {
public Controller(Device device, DesktopConnection connection, boolean clipboardAutosync, boolean powerOn) {
this.device = device;
this.connection = connection;
this.clipboardAutosync = clipboardAutosync;
this.powerOn = powerOn;
initPointers();
sender = new DeviceMessageSender(connection);
}
@ -56,7 +58,7 @@ public class Controller {
public void control() throws IOException {
// on start, power on the device
if (!Device.isScreenOn()) {
if (powerOn && !Device.isScreenOn()) {
device.pressReleaseKeycode(KeyEvent.KEYCODE_POWER, Device.INJECT_MODE_ASYNC);
// dirty hack
@ -98,7 +100,7 @@ public class Controller {
break;
case ControlMessage.TYPE_INJECT_SCROLL_EVENT:
if (device.supportsInputEvents()) {
injectScroll(msg.getPosition(), msg.getHScroll(), msg.getVScroll());
injectScroll(msg.getPosition(), msg.getHScroll(), msg.getVScroll(), msg.getButtons());
}
break;
case ControlMessage.TYPE_BACK_OR_SCREEN_ON:
@ -221,7 +223,7 @@ public class Controller {
return device.injectEvent(event, Device.INJECT_MODE_ASYNC);
}
private boolean injectScroll(Position position, int hScroll, int vScroll) {
private boolean injectScroll(Position position, int hScroll, int vScroll, int buttons) {
long now = SystemClock.uptimeMillis();
Point point = device.getPhysicalPoint(position);
if (point == null) {
@ -239,7 +241,7 @@ public class Controller {
coords.setAxisValue(MotionEvent.AXIS_VSCROLL, vScroll);
MotionEvent event = MotionEvent
.obtain(lastTouchDown, now, MotionEvent.ACTION_SCROLL, 1, pointerProperties, pointerCoords, 0, 0, 1f, 1f, DEFAULT_DEVICE_ID, 0,
.obtain(lastTouchDown, now, MotionEvent.ACTION_SCROLL, 1, pointerProperties, pointerCoords, 0, buttons, 1f, 1f, DEFAULT_DEVICE_ID, 0,
InputDevice.SOURCE_MOUSE, 0);
return device.injectEvent(event, Device.INJECT_MODE_ASYNC);
}

View file

@ -30,8 +30,13 @@ public final class DesktopConnection implements Closeable {
private DesktopConnection(LocalSocket videoSocket, LocalSocket controlSocket) throws IOException {
this.videoSocket = videoSocket;
this.controlSocket = controlSocket;
controlInputStream = controlSocket.getInputStream();
controlOutputStream = controlSocket.getOutputStream();
if (controlSocket != null) {
controlInputStream = controlSocket.getInputStream();
controlOutputStream = controlSocket.getOutputStream();
} else {
controlInputStream = null;
controlOutputStream = null;
}
videoFd = videoSocket.getFileDescriptor();
}
@ -41,50 +46,55 @@ public final class DesktopConnection implements Closeable {
return localSocket;
}
public static DesktopConnection open(Device device, boolean tunnelForward) throws IOException {
public static DesktopConnection open(boolean tunnelForward, boolean control, boolean sendDummyByte) throws IOException {
LocalSocket videoSocket;
LocalSocket controlSocket;
LocalSocket controlSocket = null;
if (tunnelForward) {
LocalServerSocket localServerSocket = new LocalServerSocket(SOCKET_NAME);
try {
videoSocket = localServerSocket.accept();
// send one byte so the client may read() to detect a connection error
videoSocket.getOutputStream().write(0);
try {
controlSocket = localServerSocket.accept();
} catch (IOException | RuntimeException e) {
videoSocket.close();
throw e;
if (sendDummyByte) {
// send one byte so the client may read() to detect a connection error
videoSocket.getOutputStream().write(0);
}
if (control) {
try {
controlSocket = localServerSocket.accept();
} catch (IOException | RuntimeException e) {
videoSocket.close();
throw e;
}
}
} finally {
localServerSocket.close();
}
} else {
videoSocket = connect(SOCKET_NAME);
try {
controlSocket = connect(SOCKET_NAME);
} catch (IOException | RuntimeException e) {
videoSocket.close();
throw e;
if (control) {
try {
controlSocket = connect(SOCKET_NAME);
} catch (IOException | RuntimeException e) {
videoSocket.close();
throw e;
}
}
}
DesktopConnection connection = new DesktopConnection(videoSocket, controlSocket);
Size videoSize = device.getScreenInfo().getVideoSize();
connection.send(Device.getDeviceName(), videoSize.getWidth(), videoSize.getHeight());
return connection;
return new DesktopConnection(videoSocket, controlSocket);
}
public void close() throws IOException {
videoSocket.shutdownInput();
videoSocket.shutdownOutput();
videoSocket.close();
controlSocket.shutdownInput();
controlSocket.shutdownOutput();
controlSocket.close();
if (controlSocket != null) {
controlSocket.shutdownInput();
controlSocket.shutdownOutput();
controlSocket.close();
}
}
private void send(String deviceName, int width, int height) throws IOException {
public void sendDeviceMeta(String deviceName, int width, int height) throws IOException {
byte[] buffer = new byte[DEVICE_NAME_FIELD_LENGTH + 4];
byte[] deviceNameBytes = deviceName.getBytes(StandardCharsets.UTF_8);

View file

@ -42,6 +42,11 @@ public final class Device {
void onClipboardTextChanged(String text);
}
private final Size deviceSize;
private final Rect crop;
private int maxSize;
private final int lockVideoOrientation;
private ScreenInfo screenInfo;
private RotationListener rotationListener;
private ClipboardListener clipboardListener;
@ -69,7 +74,12 @@ public final class Device {
int displayInfoFlags = displayInfo.getFlags();
screenInfo = ScreenInfo.computeScreenInfo(displayInfo, options.getCrop(), options.getMaxSize(), options.getLockVideoOrientation());
deviceSize = displayInfo.getSize();
crop = options.getCrop();
maxSize = options.getMaxSize();
lockVideoOrientation = options.getLockVideoOrientation();
screenInfo = ScreenInfo.computeScreenInfo(displayInfo.getRotation(), deviceSize, crop, maxSize, lockVideoOrientation);
layerStack = displayInfo.getLayerStack();
SERVICE_MANAGER.getWindowManager().registerRotationWatcher(new IRotationWatcher.Stub() {
@ -123,6 +133,11 @@ public final class Device {
}
}
public synchronized void setMaxSize(int newMaxSize) {
maxSize = newMaxSize;
screenInfo = ScreenInfo.computeScreenInfo(screenInfo.getReverseVideoRotation(), deviceSize, crop, newMaxSize, lockVideoOrientation);
}
public synchronized ScreenInfo getScreenInfo() {
return screenInfo;
}

View file

@ -12,7 +12,6 @@ public class Options {
private int lockVideoOrientation = -1;
private boolean tunnelForward;
private Rect crop;
private boolean sendFrameMeta = true; // send PTS so that the client may record properly
private boolean control = true;
private int displayId;
private boolean showTouches;
@ -21,6 +20,14 @@ public class Options {
private String encoderName;
private boolean powerOffScreenOnClose;
private boolean clipboardAutosync = true;
private boolean downsizeOnError = true;
private boolean cleanup = true;
private boolean powerOn = true;
// Options not used by the scrcpy client, but useful to use scrcpy-server directly
private boolean sendDeviceMeta = true; // send device name and size
private boolean sendFrameMeta = true; // send PTS so that the client may record properly
private boolean sendDummyByte = true; // write a byte on start to detect connection issues
public Ln.Level getLogLevel() {
return logLevel;
@ -78,14 +85,6 @@ public class Options {
this.crop = crop;
}
public boolean getSendFrameMeta() {
return sendFrameMeta;
}
public void setSendFrameMeta(boolean sendFrameMeta) {
this.sendFrameMeta = sendFrameMeta;
}
public boolean getControl() {
return control;
}
@ -149,4 +148,52 @@ public class Options {
public void setClipboardAutosync(boolean clipboardAutosync) {
this.clipboardAutosync = clipboardAutosync;
}
public boolean getDownsizeOnError() {
return downsizeOnError;
}
public void setDownsizeOnError(boolean downsizeOnError) {
this.downsizeOnError = downsizeOnError;
}
public boolean getCleanup() {
return cleanup;
}
public void setCleanup(boolean cleanup) {
this.cleanup = cleanup;
}
public boolean getPowerOn() {
return powerOn;
}
public void setPowerOn(boolean powerOn) {
this.powerOn = powerOn;
}
public boolean getSendDeviceMeta() {
return sendDeviceMeta;
}
public void setSendDeviceMeta(boolean sendDeviceMeta) {
this.sendDeviceMeta = sendDeviceMeta;
}
public boolean getSendFrameMeta() {
return sendFrameMeta;
}
public void setSendFrameMeta(boolean sendFrameMeta) {
this.sendFrameMeta = sendFrameMeta;
}
public boolean getSendDummyByte() {
return sendDummyByte;
}
public void setSendDummyByte(boolean sendDummyByte) {
this.sendDummyByte = sendDummyByte;
}
}

View file

@ -25,24 +25,33 @@ public class ScreenEncoder implements Device.RotationListener {
private static final int REPEAT_FRAME_DELAY_US = 100_000; // repeat after 100ms
private static final String KEY_MAX_FPS_TO_ENCODER = "max-fps-to-encoder";
private static final int NO_PTS = -1;
// Keep the values in descending order
private static final int[] MAX_SIZE_FALLBACK = {2560, 1920, 1600, 1280, 1024, 800};
private static final long PACKET_FLAG_CONFIG = 1L << 63;
private static final long PACKET_FLAG_KEY_FRAME = 1L << 62;
private final AtomicBoolean rotationChanged = new AtomicBoolean();
private final ByteBuffer headerBuffer = ByteBuffer.allocate(12);
private String encoderName;
private List<CodecOption> codecOptions;
private int bitRate;
private int maxFps;
private boolean sendFrameMeta;
private final String encoderName;
private final List<CodecOption> codecOptions;
private final int bitRate;
private final int maxFps;
private final boolean sendFrameMeta;
private final boolean downsizeOnError;
private long ptsOrigin;
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps, List<CodecOption> codecOptions, String encoderName) {
private boolean firstFrameSent;
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps, List<CodecOption> codecOptions, String encoderName,
boolean downsizeOnError) {
this.sendFrameMeta = sendFrameMeta;
this.bitRate = bitRate;
this.maxFps = maxFps;
this.codecOptions = codecOptions;
this.encoderName = encoderName;
this.downsizeOnError = downsizeOnError;
}
@Override
@ -81,20 +90,41 @@ public class ScreenEncoder implements Device.RotationListener {
Rect unlockedVideoRect = screenInfo.getUnlockedVideoSize().toRect();
int videoRotation = screenInfo.getVideoRotation();
int layerStack = device.getLayerStack();
setSize(format, videoRect.width(), videoRect.height());
configure(codec, format);
Surface surface = codec.createInputSurface();
setDisplaySurface(display, surface, videoRotation, contentRect, unlockedVideoRect, layerStack);
codec.start();
Surface surface = null;
try {
configure(codec, format);
surface = codec.createInputSurface();
setDisplaySurface(display, surface, videoRotation, contentRect, unlockedVideoRect, layerStack);
codec.start();
alive = encode(codec, fd);
// do not call stop() on exception, it would trigger an IllegalStateException
codec.stop();
} catch (IllegalStateException | IllegalArgumentException e) {
Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage());
if (!downsizeOnError || firstFrameSent) {
// Fail immediately
throw e;
}
int newMaxSize = chooseMaxSizeFallback(screenInfo.getVideoSize());
if (newMaxSize == 0) {
// Definitively fail
throw e;
}
// Retry with a smaller device size
Ln.i("Retrying with -m" + newMaxSize + "...");
device.setMaxSize(newMaxSize);
alive = true;
} finally {
destroyDisplay(display);
codec.release();
surface.release();
if (surface != null) {
surface.release();
}
}
} while (alive);
} finally {
@ -102,6 +132,18 @@ public class ScreenEncoder implements Device.RotationListener {
}
}
private static int chooseMaxSizeFallback(Size failedSize) {
int currentMaxSize = Math.max(failedSize.getWidth(), failedSize.getHeight());
for (int value : MAX_SIZE_FALLBACK) {
if (value < currentMaxSize) {
// We found a smaller value to reduce the video size
return value;
}
}
// No fallback, fail definitively
return 0;
}
private boolean encode(MediaCodec codec, FileDescriptor fd) throws IOException {
boolean eof = false;
MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
@ -122,6 +164,10 @@ public class ScreenEncoder implements Device.RotationListener {
}
IO.writeFully(fd, codecBuffer);
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) == 0) {
// If this is not a config packet, then it contains a frame
firstFrameSent = true;
}
}
} finally {
if (outputBufferId >= 0) {
@ -138,12 +184,15 @@ public class ScreenEncoder implements Device.RotationListener {
long pts;
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
pts = NO_PTS; // non-media data packet
pts = PACKET_FLAG_CONFIG; // non-media data packet
} else {
if (ptsOrigin == 0) {
ptsOrigin = bufferInfo.presentationTimeUs;
}
pts = bufferInfo.presentationTimeUs - ptsOrigin;
if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) {
pts |= PACKET_FLAG_KEY_FRAME;
}
}
headerBuffer.putLong(pts);

View file

@ -80,15 +80,12 @@ public final class ScreenInfo {
return new ScreenInfo(newContentRect, newUnlockedVideoSize, newDeviceRotation, lockedVideoOrientation);
}
public static ScreenInfo computeScreenInfo(DisplayInfo displayInfo, Rect crop, int maxSize, int lockedVideoOrientation) {
int rotation = displayInfo.getRotation();
public static ScreenInfo computeScreenInfo(int rotation, Size deviceSize, Rect crop, int maxSize, int lockedVideoOrientation) {
if (lockedVideoOrientation == Device.LOCK_VIDEO_ORIENTATION_INITIAL) {
// The user requested to lock the video orientation to the current orientation
lockedVideoOrientation = rotation;
}
Size deviceSize = displayInfo.getSize();
Rect contentRect = new Rect(0, 0, deviceSize.getWidth(), deviceSize.getHeight());
if (crop != null) {
if (rotation % 2 != 0) { // 180s preserve dimensions

View file

@ -1,7 +1,6 @@
package com.genymobile.scrcpy;
import android.graphics.Rect;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.os.BatteryManager;
import android.os.Build;
@ -12,7 +11,6 @@ import java.util.Locale;
public final class Server {
private Server() {
// not instantiable
}
@ -20,6 +18,7 @@ public final class Server {
private static void initAndCleanUp(Options options) {
boolean mustDisableShowTouchesOnCleanUp = false;
int restoreStayOn = -1;
boolean restoreNormalPowerMode = options.getControl(); // only restore power mode if control is enabled
if (options.getShowTouches() || options.getStayAwake()) {
Settings settings = Device.getSettings();
if (options.getShowTouches()) {
@ -51,10 +50,13 @@ public final class Server {
}
}
try {
CleanUp.configure(options.getDisplayId(), restoreStayOn, mustDisableShowTouchesOnCleanUp, true, options.getPowerOffScreenOnClose());
} catch (IOException e) {
Ln.e("Could not configure cleanup", e);
if (options.getCleanup()) {
try {
CleanUp.configure(options.getDisplayId(), restoreStayOn, mustDisableShowTouchesOnCleanUp, restoreNormalPowerMode,
options.getPowerOffScreenOnClose());
} catch (IOException e) {
Ln.e("Could not configure cleanup", e);
}
}
}
@ -66,15 +68,21 @@ public final class Server {
Thread initThread = startInitThread(options);
boolean tunnelForward = options.isTunnelForward();
boolean control = options.getControl();
boolean sendDummyByte = options.getSendDummyByte();
try (DesktopConnection connection = DesktopConnection.open(device, tunnelForward)) {
try (DesktopConnection connection = DesktopConnection.open(tunnelForward, control, sendDummyByte)) {
if (options.getSendDeviceMeta()) {
Size videoSize = device.getScreenInfo().getVideoSize();
connection.sendDeviceMeta(Device.getDeviceName(), videoSize.getWidth(), videoSize.getHeight());
}
ScreenEncoder screenEncoder = new ScreenEncoder(options.getSendFrameMeta(), options.getBitRate(), options.getMaxFps(), codecOptions,
options.getEncoderName());
options.getEncoderName(), options.getDownsizeOnError());
Thread controllerThread = null;
Thread deviceMessageSenderThread = null;
if (options.getControl()) {
final Controller controller = new Controller(device, connection, options.getClipboardAutosync());
if (control) {
final Controller controller = new Controller(device, connection, options.getClipboardAutosync(), options.getPowerOn());
// asynchronous
controllerThread = startController(controller);
@ -199,10 +207,6 @@ public final class Server {
Rect crop = parseCrop(value);
options.setCrop(crop);
break;
case "send_frame_meta":
boolean sendFrameMeta = Boolean.parseBoolean(value);
options.setSendFrameMeta(sendFrameMeta);
break;
case "control":
boolean control = Boolean.parseBoolean(value);
options.setControl(control);
@ -236,6 +240,38 @@ public final class Server {
boolean clipboardAutosync = Boolean.parseBoolean(value);
options.setClipboardAutosync(clipboardAutosync);
break;
case "downsize_on_error":
boolean downsizeOnError = Boolean.parseBoolean(value);
options.setDownsizeOnError(downsizeOnError);
break;
case "cleanup":
boolean cleanup = Boolean.parseBoolean(value);
options.setCleanup(cleanup);
break;
case "power_on":
boolean powerOn = Boolean.parseBoolean(value);
options.setPowerOn(powerOn);
break;
case "send_device_meta":
boolean sendDeviceMeta = Boolean.parseBoolean(value);
options.setSendDeviceMeta(sendDeviceMeta);
break;
case "send_frame_meta":
boolean sendFrameMeta = Boolean.parseBoolean(value);
options.setSendFrameMeta(sendFrameMeta);
break;
case "send_dummy_byte":
boolean sendDummyByte = Boolean.parseBoolean(value);
options.setSendDummyByte(sendDummyByte);
break;
case "raw_video_stream":
boolean rawVideoStream = Boolean.parseBoolean(value);
if (rawVideoStream) {
options.setSendDeviceMeta(false);
options.setSendFrameMeta(false);
options.setSendDummyByte(false);
}
break;
default:
Ln.w("Unknown server option: " + key);
break;
@ -262,16 +298,6 @@ public final class Server {
}
private static void suggestFix(Throwable e) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (e instanceof MediaCodec.CodecException) {
MediaCodec.CodecException mce = (MediaCodec.CodecException) e;
if (mce.getErrorCode() == 0xfffffc0e) {
Ln.e("The hardware encoder is not able to encode at the given definition.");
Ln.e("Try with a lower definition:");
Ln.e(" scrcpy -m 1024");
}
}
}
if (e instanceof InvalidDisplayIdException) {
InvalidDisplayIdException idie = (InvalidDisplayIdException) e;
int[] displayIds = idie.getAvailableDisplayIds();

View file

@ -2,7 +2,6 @@ package com.genymobile.scrcpy.wrappers;
import com.genymobile.scrcpy.Ln;
import android.os.IInterface;
import android.view.InputEvent;
import java.lang.reflect.InvocationTargetException;
@ -14,12 +13,12 @@ public final class InputManager {
public static final int INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT = 1;
public static final int INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH = 2;
private final IInterface manager;
private final android.hardware.input.InputManager manager;
private Method injectInputEventMethod;
private static Method setDisplayIdMethod;
public InputManager(IInterface manager) {
public InputManager(android.hardware.input.InputManager manager) {
this.manager = manager;
}

View file

@ -4,6 +4,7 @@ import android.annotation.SuppressLint;
import android.os.IBinder;
import android.os.IInterface;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@SuppressLint("PrivateApi,DiscouragedPrivateApi")
@ -56,7 +57,13 @@ public final class ServiceManager {
public InputManager getInputManager() {
if (inputManager == null) {
inputManager = new InputManager(getService("input", "android.hardware.input.IInputManager"));
try {
Method getInstanceMethod = android.hardware.input.InputManager.class.getDeclaredMethod("getInstance");
android.hardware.input.InputManager im = (android.hardware.input.InputManager) getInstanceMethod.invoke(null);
inputManager = new InputManager(im);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new AssertionError(e);
}
}
return inputManager;
}

View file

@ -128,6 +128,7 @@ public class ControlMessageReaderTest {
dos.writeShort(1920);
dos.writeInt(1);
dos.writeInt(-1);
dos.writeInt(1);
byte[] packet = bos.toByteArray();
@ -144,6 +145,7 @@ public class ControlMessageReaderTest {
Assert.assertEquals(1920, event.getPosition().getScreenSize().getHeight());
Assert.assertEquals(1, event.getHScroll());
Assert.assertEquals(-1, event.getVScroll());
Assert.assertEquals(1, event.getButtons());
}
@Test