Compare commits
39 Commits
faq
...
threadwait
Author | SHA1 | Date | |
---|---|---|---|
eb10385a2b | |||
3603939475 | |||
d76c7c3029 | |||
f2f032a494 | |||
728b976aae | |||
ff583bdde8 | |||
429153abfb | |||
5031b2c8ff | |||
4adf5fde6d | |||
e050cfdcd6 | |||
dc7c677728 | |||
3504c0016b | |||
89d1602185 | |||
566ba766af | |||
a0af402d96 | |||
600df37753 | |||
902b99174d | |||
cd69eb4a4f | |||
ae2d094362 | |||
c5f5d1e456 | |||
63286424bb | |||
da18c9cdab | |||
d3281f4b67 | |||
1982bc439b | |||
ef56cc6ff7 | |||
c0f428eb05 | |||
4794ca8ae7 | |||
96bd2c974d | |||
dc7fcf3c7a | |||
2a3a9d4ea9 | |||
ca0031cbde | |||
d1a9a76cc6 | |||
a8ceaf5284 | |||
83d48267a7 | |||
db6252e52b | |||
229eeb24a2 | |||
f9786e5034 | |||
78a320a763 | |||
7d5845196e |
@ -282,6 +282,15 @@ meson x -Dserver_debugger=true
|
||||
meson configure x -Dserver_debugger=true
|
||||
```
|
||||
|
||||
If your device runs Android 8 or below, set the `server_debugger_method` to
|
||||
`old` in addition:
|
||||
|
||||
```bash
|
||||
meson x -Dserver_debugger=true -Dserver_debugger_method=old
|
||||
# or, if x is already configured
|
||||
meson configure x -Dserver_debugger=true -Dserver_debugger_method=old
|
||||
```
|
||||
|
||||
Then recompile.
|
||||
|
||||
When you start scrcpy, it will start a debugger on port 5005 on the device.
|
||||
|
44
README.md
44
README.md
@ -158,12 +158,14 @@ scrcpy -b 2M # short version
|
||||
|
||||
#### Limit frame rate
|
||||
|
||||
On devices with Android >= 10, the capture frame rate can be limited:
|
||||
The capture frame rate can be limited:
|
||||
|
||||
```bash
|
||||
scrcpy --max-fps 15
|
||||
```
|
||||
|
||||
This is officially supported since Android 10, but may work on earlier versions.
|
||||
|
||||
#### Crop
|
||||
|
||||
The device screen may be cropped to mirror only part of the screen.
|
||||
@ -177,6 +179,21 @@ scrcpy --crop 1224:1440:0:0 # 1224x1440 at offset (0,0)
|
||||
If `--max-size` is also specified, resizing is applied after cropping.
|
||||
|
||||
|
||||
#### Lock video orientation
|
||||
|
||||
|
||||
To lock the orientation of the mirroring:
|
||||
|
||||
```bash
|
||||
scrcpy --lock-video-orientation 0 # natural orientation
|
||||
scrcpy --lock-video-orientation 1 # 90° counterclockwise
|
||||
scrcpy --lock-video-orientation 2 # 180°
|
||||
scrcpy --lock-video-orientation 3 # 90° clockwise
|
||||
```
|
||||
|
||||
This affects recording orientation.
|
||||
|
||||
|
||||
### Recording
|
||||
|
||||
It is possible to record the screen while mirroring:
|
||||
@ -244,6 +261,16 @@ scrcpy -s 192.168.0.1:5555 # short version
|
||||
|
||||
You can start several instances of _scrcpy_ for several devices.
|
||||
|
||||
#### Autostart on device connection
|
||||
|
||||
You could use [AutoAdb]:
|
||||
|
||||
```bash
|
||||
autoadb scrcpy -s '{}'
|
||||
```
|
||||
|
||||
[AutoAdb]: https://github.com/rom1v/usbaudio
|
||||
|
||||
#### SSH tunnel
|
||||
|
||||
To connect to a remote device, it is possible to connect a local `adb` client to
|
||||
@ -326,6 +353,21 @@ scrcpy --no-control
|
||||
scrcpy -n
|
||||
```
|
||||
|
||||
#### Display
|
||||
|
||||
If several displays are available, it is possible to select the display to
|
||||
mirror:
|
||||
|
||||
```bash
|
||||
scrcpy --display 1
|
||||
```
|
||||
|
||||
The list of display ids can be retrieved by:
|
||||
|
||||
```
|
||||
adb shell dumpsys display # search "mDisplayId=" in the output
|
||||
```
|
||||
|
||||
#### Turn screen off
|
||||
|
||||
It is possible to turn the device screen off while mirroring on start with a
|
||||
|
@ -76,11 +76,9 @@ cc = meson.get_compiler('c')
|
||||
|
||||
if host_machine.system() == 'windows'
|
||||
src += [ 'src/sys/win/command.c' ]
|
||||
src += [ 'src/sys/win/net.c' ]
|
||||
dependencies += cc.find_library('ws2_32')
|
||||
else
|
||||
src += [ 'src/sys/unix/command.c' ]
|
||||
src += [ 'src/sys/unix/net.c' ]
|
||||
endif
|
||||
|
||||
conf = configuration_data()
|
||||
@ -98,14 +96,21 @@ conf.set_quoted('PREFIX', get_option('prefix'))
|
||||
# directory as the executable)
|
||||
conf.set('PORTABLE', get_option('portable'))
|
||||
|
||||
# the default client TCP port for the "adb reverse" tunnel
|
||||
# the default client TCP port range for the "adb reverse" tunnel
|
||||
# overridden by option --port
|
||||
conf.set('DEFAULT_LOCAL_PORT', '27183')
|
||||
conf.set('DEFAULT_LOCAL_PORT_RANGE_FIRST', '27183')
|
||||
conf.set('DEFAULT_LOCAL_PORT_RANGE_LAST', '27199')
|
||||
|
||||
# the default max video size for both dimensions, in pixels
|
||||
# overridden by option --max-size
|
||||
conf.set('DEFAULT_MAX_SIZE', '0') # 0: unlimited
|
||||
|
||||
# the default video orientation
|
||||
# natural device orientation is 0 and each increment adds 90 degrees
|
||||
# counterclockwise
|
||||
# overridden by option --lock-video-orientation
|
||||
conf.set('DEFAULT_LOCK_VIDEO_ORIENTATION', '-1') # -1: unlocked
|
||||
|
||||
# the default video bitrate, in bits/second
|
||||
# overridden by option --bit-rate
|
||||
conf.set('DEFAULT_BIT_RATE', '8000000') # 8Mbps
|
||||
@ -119,6 +124,9 @@ conf.set('WINDOWS_NOCONSOLE', get_option('windows_noconsole'))
|
||||
# run a server debugger and wait for a client to be attached
|
||||
conf.set('SERVER_DEBUGGER', get_option('server_debugger'))
|
||||
|
||||
# select the debugger method ('old' for Android < 9, 'new' for Android >= 9)
|
||||
conf.set('SERVER_DEBUGGER_METHOD_NEW', get_option('server_debugger_method') == 'new')
|
||||
|
||||
configure_file(configuration: conf, output: 'config.h')
|
||||
|
||||
src_dir = include_directories('src')
|
||||
|
27
app/scrcpy.1
27
app/scrcpy.1
@ -33,6 +33,15 @@ The values are expressed in the device natural orientation (typically, portrait
|
||||
.B \-\-max\-size
|
||||
value is computed on the cropped size.
|
||||
|
||||
.TP
|
||||
.BI "\-\-display " id
|
||||
Specify the display id to mirror.
|
||||
|
||||
The list of possible display ids can be listed by "adb shell dumpsys display"
|
||||
(search "mDisplayId=" in the output).
|
||||
|
||||
Default is 0.
|
||||
|
||||
.TP
|
||||
.B \-f, \-\-fullscreen
|
||||
Start in fullscreen.
|
||||
@ -41,9 +50,15 @@ Start in fullscreen.
|
||||
.B \-h, \-\-help
|
||||
Print this help.
|
||||
|
||||
.TP
|
||||
.BI "\-\-lock\-video\-orientation " value
|
||||
Lock video orientation to \fIvalue\fR. Values are integers in the range [-1..3]. Natural device orientation is 0 and each increment adds 90 degrees counterclockwise.
|
||||
|
||||
Default is -1 (unlocked).
|
||||
|
||||
.TP
|
||||
.BI "\-\-max\-fps " value
|
||||
Limit the framerate of screen capture (only supported on devices with Android >= 10).
|
||||
Limit the framerate of screen capture (officially supported since Android 10, but may work on earlier versions).
|
||||
|
||||
.TP
|
||||
.BI "\-m, \-\-max\-size " value
|
||||
@ -60,10 +75,10 @@ Disable device control (mirror the device in read\-only).
|
||||
Do not display device (only when screen recording is enabled).
|
||||
|
||||
.TP
|
||||
.BI "\-p, \-\-port " port
|
||||
Set the TCP port the client listens on.
|
||||
.BI "\-p, \-\-port " port[:port]
|
||||
Set the TCP port (range) used by the client to listen.
|
||||
|
||||
Default is 27183.
|
||||
Default is 27183:27199.
|
||||
|
||||
.TP
|
||||
.B \-\-prefer\-text
|
||||
@ -125,13 +140,13 @@ Set a custom window title.
|
||||
.BI "\-\-window\-x " value
|
||||
Set the initial window horizontal position.
|
||||
|
||||
Default is -1 (automatic).\n
|
||||
Default is "auto".\n
|
||||
|
||||
.TP
|
||||
.BI "\-\-window\-y " value
|
||||
Set the initial window vertical position.
|
||||
|
||||
Default is -1 (automatic).\n
|
||||
Default is "auto".\n
|
||||
|
||||
.TP
|
||||
.BI "\-\-window\-width " value
|
||||
|
130
app/src/cli.c
130
app/src/cli.c
@ -1,5 +1,6 @@
|
||||
#include "cli.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <getopt.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
@ -35,15 +36,30 @@ scrcpy_print_usage(const char *arg0) {
|
||||
" (typically, portrait for a phone, landscape for a tablet).\n"
|
||||
" Any --max-size value is computed on the cropped size.\n"
|
||||
"\n"
|
||||
" --display id\n"
|
||||
" Specify the display id to mirror.\n"
|
||||
"\n"
|
||||
" The list of possible display ids can be listed by:\n"
|
||||
" adb shell dumpsys display\n"
|
||||
" (search \"mDisplayId=\" in the output)\n"
|
||||
"\n"
|
||||
" Default is 0.\n"
|
||||
"\n"
|
||||
" -f, --fullscreen\n"
|
||||
" Start in fullscreen.\n"
|
||||
"\n"
|
||||
" -h, --help\n"
|
||||
" Print this help.\n"
|
||||
"\n"
|
||||
" --lock-video-orientation value\n"
|
||||
" Lock video orientation to value. Values are integers in the\n"
|
||||
" range [-1..3]. Natural device orientation is 0 and each\n"
|
||||
" increment adds 90 degrees counterclockwise.\n"
|
||||
" Default is %d%s.\n"
|
||||
"\n"
|
||||
" --max-fps value\n"
|
||||
" Limit the frame rate of screen capture (only supported on\n"
|
||||
" devices with Android >= 10).\n"
|
||||
" Limit the frame rate of screen capture (officially supported\n"
|
||||
" since Android 10, but may work on earlier versions).\n"
|
||||
"\n"
|
||||
" -m, --max-size value\n"
|
||||
" Limit both the width and height of the video to value. The\n"
|
||||
@ -58,9 +74,9 @@ scrcpy_print_usage(const char *arg0) {
|
||||
" Do not display device (only when screen recording is\n"
|
||||
" enabled).\n"
|
||||
"\n"
|
||||
" -p, --port port\n"
|
||||
" Set the TCP port the client listens on.\n"
|
||||
" Default is %d.\n"
|
||||
" -p, --port port[:port]\n"
|
||||
" Set the TCP port (range) used by the client to listen.\n"
|
||||
" Default is %d:%d.\n"
|
||||
"\n"
|
||||
" --prefer-text\n"
|
||||
" Inject alpha characters and space as text events instead of\n"
|
||||
@ -110,11 +126,11 @@ scrcpy_print_usage(const char *arg0) {
|
||||
"\n"
|
||||
" --window-x value\n"
|
||||
" Set the initial window horizontal position.\n"
|
||||
" Default is -1 (automatic).\n"
|
||||
" Default is \"auto\".\n"
|
||||
"\n"
|
||||
" --window-y value\n"
|
||||
" Set the initial window vertical position.\n"
|
||||
" Default is -1 (automatic).\n"
|
||||
" Default is \"auto\".\n"
|
||||
"\n"
|
||||
" --window-width value\n"
|
||||
" Set the initial window width.\n"
|
||||
@ -192,8 +208,9 @@ scrcpy_print_usage(const char *arg0) {
|
||||
"\n",
|
||||
arg0,
|
||||
DEFAULT_BIT_RATE,
|
||||
DEFAULT_LOCK_VIDEO_ORIENTATION, DEFAULT_LOCK_VIDEO_ORIENTATION >= 0 ? "" : " (unlocked)",
|
||||
DEFAULT_MAX_SIZE, DEFAULT_MAX_SIZE ? "" : " (unlimited)",
|
||||
DEFAULT_LOCAL_PORT);
|
||||
DEFAULT_LOCAL_PORT_RANGE_FIRST, DEFAULT_LOCAL_PORT_RANGE_LAST);
|
||||
}
|
||||
|
||||
static bool
|
||||
@ -221,6 +238,27 @@ parse_integer_arg(const char *s, long *out, bool accept_suffix, long min,
|
||||
return true;
|
||||
}
|
||||
|
||||
static size_t
|
||||
parse_integers_arg(const char *s, size_t max_items, long *out, long min,
|
||||
long max, const char *name) {
|
||||
size_t count = parse_integers(s, ':', max_items, out);
|
||||
if (!count) {
|
||||
LOGE("Could not parse %s: %s", name, s);
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
long value = out[i];
|
||||
if (value < min || value > max) {
|
||||
LOGE("Could not parse %s: value (%ld) out-of-range (%ld; %ld)",
|
||||
name, value, min, max);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_bit_rate(const char *s, uint32_t *bit_rate) {
|
||||
long value;
|
||||
@ -260,9 +298,30 @@ parse_max_fps(const char *s, uint16_t *max_fps) {
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_window_position(const char *s, int16_t *position) {
|
||||
parse_lock_video_orientation(const char *s, int8_t *lock_video_orientation) {
|
||||
long value;
|
||||
bool ok = parse_integer_arg(s, &value, false, -1, 0x7FFF,
|
||||
bool ok = parse_integer_arg(s, &value, false, -1, 3,
|
||||
"lock video orientation");
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*lock_video_orientation = (int8_t) value;
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_window_position(const char *s, int16_t *position) {
|
||||
// special value for "auto"
|
||||
static_assert(WINDOW_POSITION_UNDEFINED == -0x8000, "unexpected value");
|
||||
|
||||
if (!strcmp(s, "auto")) {
|
||||
*position = WINDOW_POSITION_UNDEFINED;
|
||||
return true;
|
||||
}
|
||||
|
||||
long value;
|
||||
bool ok = parse_integer_arg(s, &value, false, -0x7FFF, 0x7FFF,
|
||||
"window position");
|
||||
if (!ok) {
|
||||
return false;
|
||||
@ -286,14 +345,42 @@ parse_window_dimension(const char *s, uint16_t *dimension) {
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_port(const char *s, uint16_t *port) {
|
||||
parse_port_range(const char *s, struct port_range *port_range) {
|
||||
long values[2];
|
||||
size_t count = parse_integers_arg(s, 2, values, 0, 0xFFFF, "port");
|
||||
if (!count) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint16_t v0 = (uint16_t) values[0];
|
||||
if (count == 1) {
|
||||
port_range->first = v0;
|
||||
port_range->last = v0;
|
||||
return true;
|
||||
}
|
||||
|
||||
assert(count == 2);
|
||||
uint16_t v1 = (uint16_t) values[1];
|
||||
if (v0 < v1) {
|
||||
port_range->first = v0;
|
||||
port_range->last = v1;
|
||||
} else {
|
||||
port_range->first = v1;
|
||||
port_range->last = v0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool
|
||||
parse_display_id(const char *s, uint16_t *display_id) {
|
||||
long value;
|
||||
bool ok = parse_integer_arg(s, &value, false, 0, 0xFFFF, "port");
|
||||
bool ok = parse_integer_arg(s, &value, false, 0, 0xFFFF, "display id");
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*port = (uint16_t) value;
|
||||
*display_id = (uint16_t) value;
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -340,6 +427,8 @@ guess_record_format(const char *filename) {
|
||||
#define OPT_WINDOW_HEIGHT 1010
|
||||
#define OPT_WINDOW_BORDERLESS 1011
|
||||
#define OPT_MAX_FPS 1012
|
||||
#define OPT_LOCK_VIDEO_ORIENTATION 1013
|
||||
#define OPT_DISPLAY_ID 1014
|
||||
|
||||
bool
|
||||
scrcpy_parse_args(struct scrcpy_cli_args *args, int argc, char *argv[]) {
|
||||
@ -347,8 +436,11 @@ scrcpy_parse_args(struct scrcpy_cli_args *args, int argc, char *argv[]) {
|
||||
{"always-on-top", no_argument, NULL, OPT_ALWAYS_ON_TOP},
|
||||
{"bit-rate", required_argument, NULL, 'b'},
|
||||
{"crop", required_argument, NULL, OPT_CROP},
|
||||
{"display", required_argument, NULL, OPT_DISPLAY_ID},
|
||||
{"fullscreen", no_argument, NULL, 'f'},
|
||||
{"help", no_argument, NULL, 'h'},
|
||||
{"lock-video-orientation", required_argument, NULL,
|
||||
OPT_LOCK_VIDEO_ORIENTATION},
|
||||
{"max-fps", required_argument, NULL, OPT_MAX_FPS},
|
||||
{"max-size", required_argument, NULL, 'm'},
|
||||
{"no-control", no_argument, NULL, 'n'},
|
||||
@ -393,6 +485,11 @@ scrcpy_parse_args(struct scrcpy_cli_args *args, int argc, char *argv[]) {
|
||||
case OPT_CROP:
|
||||
opts->crop = optarg;
|
||||
break;
|
||||
case OPT_DISPLAY_ID:
|
||||
if (!parse_display_id(optarg, &opts->display_id)) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case 'f':
|
||||
opts->fullscreen = true;
|
||||
break;
|
||||
@ -417,6 +514,11 @@ scrcpy_parse_args(struct scrcpy_cli_args *args, int argc, char *argv[]) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case OPT_LOCK_VIDEO_ORIENTATION:
|
||||
if (!parse_lock_video_orientation(optarg, &opts->lock_video_orientation)) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case 'n':
|
||||
opts->control = false;
|
||||
break;
|
||||
@ -424,7 +526,7 @@ scrcpy_parse_args(struct scrcpy_cli_args *args, int argc, char *argv[]) {
|
||||
opts->display = false;
|
||||
break;
|
||||
case 'p':
|
||||
if (!parse_port(optarg, &opts->port)) {
|
||||
if (!parse_port_range(optarg, &opts->port_range)) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
|
@ -4,9 +4,6 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "common.h"
|
||||
@ -58,6 +55,32 @@ argv_to_string(const char *const *argv, char *buf, size_t bufsize) {
|
||||
return idx;
|
||||
}
|
||||
|
||||
static void
|
||||
show_adb_installation_msg() {
|
||||
#ifndef __WINDOWS__
|
||||
static const struct {
|
||||
const char *binary;
|
||||
const char *command;
|
||||
} pkg_managers[] = {
|
||||
{"apt", "apt install adb"},
|
||||
{"apt-get", "apt-get install adb"},
|
||||
{"brew", "brew cask install android-platform-tools"},
|
||||
{"dnf", "dnf install android-tools"},
|
||||
{"emerge", "emerge dev-util/android-tools"},
|
||||
{"pacman", "pacman -S android-tools"},
|
||||
};
|
||||
for (size_t i = 0; i < ARRAY_LEN(pkg_managers); ++i) {
|
||||
if (cmd_search(pkg_managers[i].binary)) {
|
||||
LOGI("You may install 'adb' by \"%s\"", pkg_managers[i].command);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
LOGI("You may download and install 'adb' from "
|
||||
"https://developer.android.com/studio/releases/platform-tools");
|
||||
}
|
||||
|
||||
static void
|
||||
show_adb_err_msg(enum process_result err, const char *const argv[]) {
|
||||
char buf[512];
|
||||
@ -71,6 +94,7 @@ show_adb_err_msg(enum process_result err, const char *const argv[]) {
|
||||
LOGE("Command not found: %s", buf);
|
||||
LOGE("(make 'adb' accessible from your PATH or define its full"
|
||||
"path in the ADB environment variable)");
|
||||
show_adb_installation_msg();
|
||||
break;
|
||||
case PROCESS_SUCCESS:
|
||||
// do nothing
|
||||
@ -205,14 +229,3 @@ process_check_success(process_t proc, const char *name) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool
|
||||
is_regular_file(const char *path) {
|
||||
struct stat path_stat;
|
||||
int r = stat(path, &path_stat);
|
||||
if (r) {
|
||||
perror("stat");
|
||||
return false;
|
||||
}
|
||||
return S_ISREG(path_stat.st_mode);
|
||||
}
|
||||
|
@ -43,6 +43,11 @@ enum process_result {
|
||||
PROCESS_ERROR_MISSING_BINARY,
|
||||
};
|
||||
|
||||
#ifndef __WINDOWS__
|
||||
bool
|
||||
cmd_search(const char *file);
|
||||
#endif
|
||||
|
||||
enum process_result
|
||||
cmd_execute(const char *const argv[], process_t *process);
|
||||
|
||||
|
@ -27,4 +27,9 @@ struct position {
|
||||
struct point point;
|
||||
};
|
||||
|
||||
struct port_range {
|
||||
uint16_t first;
|
||||
uint16_t last;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
@ -94,6 +94,23 @@ convert_keycode(SDL_Keycode from, enum android_keycode *to, uint16_t mod,
|
||||
MAP(SDLK_UP, AKEYCODE_DPAD_UP);
|
||||
}
|
||||
|
||||
if (!(mod & (KMOD_NUM | KMOD_SHIFT))) {
|
||||
// Handle Numpad events when Num Lock is disabled
|
||||
// If SHIFT is pressed, a text event will be sent instead
|
||||
switch(from) {
|
||||
MAP(SDLK_KP_0, AKEYCODE_INSERT);
|
||||
MAP(SDLK_KP_1, AKEYCODE_MOVE_END);
|
||||
MAP(SDLK_KP_2, AKEYCODE_DPAD_DOWN);
|
||||
MAP(SDLK_KP_3, AKEYCODE_PAGE_DOWN);
|
||||
MAP(SDLK_KP_4, AKEYCODE_DPAD_LEFT);
|
||||
MAP(SDLK_KP_6, AKEYCODE_DPAD_RIGHT);
|
||||
MAP(SDLK_KP_7, AKEYCODE_MOVE_HOME);
|
||||
MAP(SDLK_KP_8, AKEYCODE_DPAD_UP);
|
||||
MAP(SDLK_KP_9, AKEYCODE_PAGE_UP);
|
||||
MAP(SDLK_KP_PERIOD, AKEYCODE_FORWARD_DEL);
|
||||
}
|
||||
}
|
||||
|
||||
if (prefer_text) {
|
||||
// do not forward alpha and space key events
|
||||
return false;
|
||||
|
@ -23,7 +23,7 @@ fps_counter_init(struct fps_counter *counter) {
|
||||
}
|
||||
|
||||
counter->thread = NULL;
|
||||
SDL_AtomicSet(&counter->started, 0);
|
||||
atomic_init(&counter->started, 0);
|
||||
// no need to initialize the other fields, they are unused until started
|
||||
|
||||
return true;
|
||||
@ -35,6 +35,16 @@ fps_counter_destroy(struct fps_counter *counter) {
|
||||
SDL_DestroyMutex(counter->mutex);
|
||||
}
|
||||
|
||||
static inline bool
|
||||
is_started(struct fps_counter *counter) {
|
||||
return atomic_load_explicit(&counter->started, memory_order_acquire);
|
||||
}
|
||||
|
||||
static inline void
|
||||
set_started(struct fps_counter *counter, bool started) {
|
||||
atomic_store_explicit(&counter->started, started, memory_order_release);
|
||||
}
|
||||
|
||||
// must be called with mutex locked
|
||||
static void
|
||||
display_fps(struct fps_counter *counter) {
|
||||
@ -70,10 +80,10 @@ run_fps_counter(void *data) {
|
||||
|
||||
mutex_lock(counter->mutex);
|
||||
while (!counter->interrupted) {
|
||||
while (!counter->interrupted && !SDL_AtomicGet(&counter->started)) {
|
||||
while (!counter->interrupted && !is_started(counter)) {
|
||||
cond_wait(counter->state_cond, counter->mutex);
|
||||
}
|
||||
while (!counter->interrupted && SDL_AtomicGet(&counter->started)) {
|
||||
while (!counter->interrupted && is_started(counter)) {
|
||||
uint32_t now = SDL_GetTicks();
|
||||
check_interval_expired(counter, now);
|
||||
|
||||
@ -96,7 +106,7 @@ fps_counter_start(struct fps_counter *counter) {
|
||||
counter->nr_skipped = 0;
|
||||
mutex_unlock(counter->mutex);
|
||||
|
||||
SDL_AtomicSet(&counter->started, 1);
|
||||
set_started(counter, true);
|
||||
cond_signal(counter->state_cond);
|
||||
|
||||
// counter->thread is always accessed from the same thread, no need to lock
|
||||
@ -114,13 +124,13 @@ fps_counter_start(struct fps_counter *counter) {
|
||||
|
||||
void
|
||||
fps_counter_stop(struct fps_counter *counter) {
|
||||
SDL_AtomicSet(&counter->started, 0);
|
||||
set_started(counter, false);
|
||||
cond_signal(counter->state_cond);
|
||||
}
|
||||
|
||||
bool
|
||||
fps_counter_is_started(struct fps_counter *counter) {
|
||||
return SDL_AtomicGet(&counter->started);
|
||||
return is_started(counter);
|
||||
}
|
||||
|
||||
void
|
||||
@ -145,7 +155,7 @@ fps_counter_join(struct fps_counter *counter) {
|
||||
|
||||
void
|
||||
fps_counter_add_rendered_frame(struct fps_counter *counter) {
|
||||
if (!SDL_AtomicGet(&counter->started)) {
|
||||
if (!is_started(counter)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -158,7 +168,7 @@ fps_counter_add_rendered_frame(struct fps_counter *counter) {
|
||||
|
||||
void
|
||||
fps_counter_add_skipped_frame(struct fps_counter *counter) {
|
||||
if (!SDL_AtomicGet(&counter->started)) {
|
||||
if (!is_started(counter)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
#ifndef FPSCOUNTER_H
|
||||
#define FPSCOUNTER_H
|
||||
|
||||
#include <stdatomic.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <SDL2/SDL_atomic.h>
|
||||
#include <SDL2/SDL_mutex.h>
|
||||
#include <SDL2/SDL_thread.h>
|
||||
|
||||
@ -16,7 +16,7 @@ struct fps_counter {
|
||||
|
||||
// atomic so that we can check without locking the mutex
|
||||
// if the FPS counter is disabled, we don't want to lock unnecessarily
|
||||
SDL_atomic_t started;
|
||||
atomic_bool started;
|
||||
|
||||
// the following fields are protected by the mutex
|
||||
bool interrupted;
|
||||
|
@ -60,9 +60,9 @@ sdl_init_and_configure(bool display) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Use the best available scale quality
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2")) {
|
||||
LOGW("Could not enable bilinear filtering");
|
||||
// Linear filtering
|
||||
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) {
|
||||
LOGW("Could not enable linear filtering");
|
||||
}
|
||||
|
||||
#ifdef SCRCPY_SDL_HAS_HINT_MOUSE_FOCUS_CLICKTHROUGH
|
||||
@ -280,11 +280,13 @@ scrcpy(const struct scrcpy_options *options) {
|
||||
bool record = !!options->record_filename;
|
||||
struct server_params params = {
|
||||
.crop = options->crop,
|
||||
.local_port = options->port,
|
||||
.port_range = options->port_range,
|
||||
.max_size = options->max_size,
|
||||
.bit_rate = options->bit_rate,
|
||||
.max_fps = options->max_fps,
|
||||
.lock_video_orientation = options->lock_video_orientation,
|
||||
.control = options->control,
|
||||
.display_id = options->display_id,
|
||||
};
|
||||
if (!server_start(&server, options->serial, ¶ms)) {
|
||||
return false;
|
||||
|
@ -5,6 +5,7 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "common.h"
|
||||
#include "input_manager.h"
|
||||
#include "recorder.h"
|
||||
|
||||
@ -15,14 +16,16 @@ struct scrcpy_options {
|
||||
const char *window_title;
|
||||
const char *push_target;
|
||||
enum recorder_format record_format;
|
||||
uint16_t port;
|
||||
struct port_range port_range;
|
||||
uint16_t max_size;
|
||||
uint32_t bit_rate;
|
||||
uint16_t max_fps;
|
||||
int16_t window_x;
|
||||
int16_t window_y;
|
||||
int8_t lock_video_orientation;
|
||||
int16_t window_x; // WINDOW_POSITION_UNDEFINED for "auto"
|
||||
int16_t window_y; // WINDOW_POSITION_UNDEFINED for "auto"
|
||||
uint16_t window_width;
|
||||
uint16_t window_height;
|
||||
uint16_t display_id;
|
||||
bool show_touches;
|
||||
bool fullscreen;
|
||||
bool always_on_top;
|
||||
@ -41,14 +44,19 @@ struct scrcpy_options {
|
||||
.window_title = NULL, \
|
||||
.push_target = NULL, \
|
||||
.record_format = RECORDER_FORMAT_AUTO, \
|
||||
.port = DEFAULT_LOCAL_PORT, \
|
||||
.port_range = { \
|
||||
.first = DEFAULT_LOCAL_PORT_RANGE_FIRST, \
|
||||
.last = DEFAULT_LOCAL_PORT_RANGE_LAST, \
|
||||
}, \
|
||||
.max_size = DEFAULT_MAX_SIZE, \
|
||||
.bit_rate = DEFAULT_BIT_RATE, \
|
||||
.max_fps = 0, \
|
||||
.window_x = -1, \
|
||||
.window_y = -1, \
|
||||
.lock_video_orientation = DEFAULT_LOCK_VIDEO_ORIENTATION, \
|
||||
.window_x = WINDOW_POSITION_UNDEFINED, \
|
||||
.window_y = WINDOW_POSITION_UNDEFINED, \
|
||||
.window_width = 0, \
|
||||
.window_height = 0, \
|
||||
.display_id = 0, \
|
||||
.show_touches = false, \
|
||||
.fullscreen = false, \
|
||||
.always_on_top = false, \
|
||||
|
@ -186,8 +186,10 @@ screen_init_rendering(struct screen *screen, const char *window_title,
|
||||
window_flags |= SDL_WINDOW_BORDERLESS;
|
||||
}
|
||||
|
||||
int x = window_x != -1 ? window_x : (int) SDL_WINDOWPOS_UNDEFINED;
|
||||
int y = window_y != -1 ? window_y : (int) SDL_WINDOWPOS_UNDEFINED;
|
||||
int x = window_x != WINDOW_POSITION_UNDEFINED
|
||||
? window_x : (int) SDL_WINDOWPOS_UNDEFINED;
|
||||
int y = window_y != WINDOW_POSITION_UNDEFINED
|
||||
? window_y : (int) SDL_WINDOWPOS_UNDEFINED;
|
||||
screen->window = SDL_CreateWindow(window_title, x, y,
|
||||
window_size.width, window_size.height,
|
||||
window_flags);
|
||||
|
@ -8,6 +8,8 @@
|
||||
#include "config.h"
|
||||
#include "common.h"
|
||||
|
||||
#define WINDOW_POSITION_UNDEFINED (-0x8000)
|
||||
|
||||
struct video_buffer;
|
||||
|
||||
struct screen {
|
||||
@ -53,6 +55,7 @@ void
|
||||
screen_init(struct screen *screen);
|
||||
|
||||
// initialize screen, create window, renderer and texture (window is hidden)
|
||||
// window_x and window_y accept WINDOW_POSITION_UNDEFINED
|
||||
bool
|
||||
screen_init_rendering(struct screen *screen, const char *window_title,
|
||||
struct size frame_size, bool always_on_top,
|
||||
|
273
app/src/server.c
273
app/src/server.c
@ -5,12 +5,15 @@
|
||||
#include <inttypes.h>
|
||||
#include <libgen.h>
|
||||
#include <stdio.h>
|
||||
#include <SDL2/SDL_thread.h>
|
||||
#include <SDL2/SDL_timer.h>
|
||||
#include <SDL2/SDL_platform.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "command.h"
|
||||
#include "util/log.h"
|
||||
#include "util/net.h"
|
||||
#include "util/str_util.h"
|
||||
|
||||
#define SOCKET_NAME "scrcpy"
|
||||
#define SERVER_FILENAME "scrcpy-server"
|
||||
@ -18,20 +21,39 @@
|
||||
#define DEFAULT_SERVER_PATH PREFIX "/share/scrcpy/" SERVER_FILENAME
|
||||
#define DEVICE_SERVER_PATH "/data/local/tmp/scrcpy-server.jar"
|
||||
|
||||
static const char *
|
||||
static char *
|
||||
get_server_path(void) {
|
||||
#ifdef __WINDOWS__
|
||||
const wchar_t *server_path_env = _wgetenv(L"SCRCPY_SERVER_PATH");
|
||||
#else
|
||||
const char *server_path_env = getenv("SCRCPY_SERVER_PATH");
|
||||
#endif
|
||||
if (server_path_env) {
|
||||
LOGD("Using SCRCPY_SERVER_PATH: %s", server_path_env);
|
||||
// if the envvar is set, use it
|
||||
return server_path_env;
|
||||
#ifdef __WINDOWS__
|
||||
char *server_path = utf8_from_wide_char(server_path_env);
|
||||
#else
|
||||
char *server_path = SDL_strdup(server_path_env);
|
||||
#endif
|
||||
if (!server_path) {
|
||||
LOGE("Could not allocate memory");
|
||||
return NULL;
|
||||
}
|
||||
LOGD("Using SCRCPY_SERVER_PATH: %s", server_path);
|
||||
return server_path;
|
||||
}
|
||||
|
||||
#ifndef PORTABLE
|
||||
LOGD("Using server: " DEFAULT_SERVER_PATH);
|
||||
char *server_path = SDL_strdup(DEFAULT_SERVER_PATH);
|
||||
if (!server_path) {
|
||||
LOGE("Could not allocate memory");
|
||||
return NULL;
|
||||
}
|
||||
// the absolute path is hardcoded
|
||||
return DEFAULT_SERVER_PATH;
|
||||
return server_path;
|
||||
#else
|
||||
|
||||
// use scrcpy-server in the same directory as the executable
|
||||
char *executable_path = get_executable_path();
|
||||
if (!executable_path) {
|
||||
@ -67,12 +89,17 @@ get_server_path(void) {
|
||||
|
||||
static bool
|
||||
push_server(const char *serial) {
|
||||
const char *server_path = get_server_path();
|
||||
char *server_path = get_server_path();
|
||||
if (!server_path) {
|
||||
return false;
|
||||
}
|
||||
if (!is_regular_file(server_path)) {
|
||||
LOGE("'%s' does not exist or is not a regular file\n", server_path);
|
||||
SDL_free(server_path);
|
||||
return false;
|
||||
}
|
||||
process_t process = adb_push(serial, server_path, DEVICE_SERVER_PATH);
|
||||
SDL_free(server_path);
|
||||
return process_check_success(process, "adb push");
|
||||
}
|
||||
|
||||
@ -100,17 +127,6 @@ disable_tunnel_forward(const char *serial, uint16_t local_port) {
|
||||
return process_check_success(process, "adb forward --remove");
|
||||
}
|
||||
|
||||
static bool
|
||||
enable_tunnel(struct server *server) {
|
||||
if (enable_tunnel_reverse(server->serial, server->local_port)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
LOGW("'adb reverse' failed, fallback to 'adb forward'");
|
||||
server->tunnel_forward = true;
|
||||
return enable_tunnel_forward(server->serial, server->local_port);
|
||||
}
|
||||
|
||||
static bool
|
||||
disable_tunnel(struct server *server) {
|
||||
if (server->tunnel_forward) {
|
||||
@ -119,21 +135,125 @@ disable_tunnel(struct server *server) {
|
||||
return disable_tunnel_reverse(server->serial);
|
||||
}
|
||||
|
||||
static socket_t
|
||||
listen_on_port(uint16_t port) {
|
||||
#define IPV4_LOCALHOST 0x7F000001
|
||||
return net_listen(IPV4_LOCALHOST, port, 1);
|
||||
}
|
||||
|
||||
static bool
|
||||
enable_tunnel_reverse_any_port(struct server *server,
|
||||
struct port_range port_range) {
|
||||
uint16_t port = port_range.first;
|
||||
for (;;) {
|
||||
if (!enable_tunnel_reverse(server->serial, port)) {
|
||||
// the command itself failed, it will fail on any port
|
||||
return false;
|
||||
}
|
||||
|
||||
// At the application level, the device part is "the server" because it
|
||||
// serves video stream and control. However, at the network level, the
|
||||
// client listens and the server connects to the client. That way, the
|
||||
// client can listen before starting the server app, so there is no
|
||||
// need to try to connect until the server socket is listening on the
|
||||
// device.
|
||||
server->server_socket = listen_on_port(port);
|
||||
if (server->server_socket != INVALID_SOCKET) {
|
||||
// success
|
||||
server->local_port = port;
|
||||
return true;
|
||||
}
|
||||
|
||||
// failure, disable tunnel and try another port
|
||||
if (!disable_tunnel_reverse(server->serial)) {
|
||||
LOGW("Could not remove reverse tunnel on port %" PRIu16, port);
|
||||
}
|
||||
|
||||
// check before incrementing to avoid overflow on port 65535
|
||||
if (port < port_range.last) {
|
||||
LOGW("Could not listen on port %" PRIu16", retrying on %" PRIu16,
|
||||
port, port + 1);
|
||||
port++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (port_range.first == port_range.last) {
|
||||
LOGE("Could not listen on port %" PRIu16, port_range.first);
|
||||
} else {
|
||||
LOGE("Could not listen on any port in range %" PRIu16 ":%" PRIu16,
|
||||
port_range.first, port_range.last);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
enable_tunnel_forward_any_port(struct server *server,
|
||||
struct port_range port_range) {
|
||||
server->tunnel_forward = true;
|
||||
uint16_t port = port_range.first;
|
||||
for (;;) {
|
||||
if (enable_tunnel_forward(server->serial, port)) {
|
||||
// success
|
||||
server->local_port = port;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (port < port_range.last) {
|
||||
LOGW("Could not forward port %" PRIu16", retrying on %" PRIu16,
|
||||
port, port + 1);
|
||||
port++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (port_range.first == port_range.last) {
|
||||
LOGE("Could not forward port %" PRIu16, port_range.first);
|
||||
} else {
|
||||
LOGE("Could not forward any port in range %" PRIu16 ":%" PRIu16,
|
||||
port_range.first, port_range.last);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool
|
||||
enable_tunnel_any_port(struct server *server, struct port_range port_range) {
|
||||
if (enable_tunnel_reverse_any_port(server, port_range)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// if "adb reverse" does not work (e.g. over "adb connect"), it fallbacks to
|
||||
// "adb forward", so the app socket is the client
|
||||
|
||||
LOGW("'adb reverse' failed, fallback to 'adb forward'");
|
||||
return enable_tunnel_forward_any_port(server, port_range);
|
||||
}
|
||||
|
||||
static process_t
|
||||
execute_server(struct server *server, const struct server_params *params) {
|
||||
char max_size_string[6];
|
||||
char bit_rate_string[11];
|
||||
char max_fps_string[6];
|
||||
char lock_video_orientation_string[3];
|
||||
char display_id_string[6];
|
||||
sprintf(max_size_string, "%"PRIu16, params->max_size);
|
||||
sprintf(bit_rate_string, "%"PRIu32, params->bit_rate);
|
||||
sprintf(max_fps_string, "%"PRIu16, params->max_fps);
|
||||
sprintf(lock_video_orientation_string, "%"PRIi8, params->lock_video_orientation);
|
||||
sprintf(display_id_string, "%"PRIu16, params->display_id);
|
||||
const char *const cmd[] = {
|
||||
"shell",
|
||||
"CLASSPATH=" DEVICE_SERVER_PATH,
|
||||
"app_process",
|
||||
#ifdef SERVER_DEBUGGER
|
||||
# define SERVER_DEBUGGER_PORT "5005"
|
||||
# ifdef SERVER_DEBUGGER_METHOD_NEW
|
||||
/* Android 9 and above */
|
||||
"-XjdwpProvider:internal -XjdwpOptions:transport=dt_socket,suspend=y,server=y,address="
|
||||
# else
|
||||
/* Android 8 and below */
|
||||
"-agentlib:jdwp=transport=dt_socket,suspend=y,server=y,address="
|
||||
# endif
|
||||
SERVER_DEBUGGER_PORT,
|
||||
#endif
|
||||
"/", // unused
|
||||
@ -142,10 +262,12 @@ execute_server(struct server *server, const struct server_params *params) {
|
||||
max_size_string,
|
||||
bit_rate_string,
|
||||
max_fps_string,
|
||||
lock_video_orientation_string,
|
||||
server->tunnel_forward ? "true" : "false",
|
||||
params->crop ? params->crop : "-",
|
||||
"true", // always send frame meta (packet boundaries + timestamp)
|
||||
params->control ? "true" : "false",
|
||||
display_id_string,
|
||||
};
|
||||
#ifdef SERVER_DEBUGGER
|
||||
LOGI("Server debugger waiting for a client on device port "
|
||||
@ -161,13 +283,6 @@ execute_server(struct server *server, const struct server_params *params) {
|
||||
return adb_execute(server->serial, cmd, sizeof(cmd) / sizeof(cmd[0]));
|
||||
}
|
||||
|
||||
#define IPV4_LOCALHOST 0x7F000001
|
||||
|
||||
static socket_t
|
||||
listen_on_port(uint16_t port) {
|
||||
return net_listen(IPV4_LOCALHOST, port, 1);
|
||||
}
|
||||
|
||||
static socket_t
|
||||
connect_and_read_byte(uint16_t port) {
|
||||
socket_t socket = net_connect(IPV4_LOCALHOST, port);
|
||||
@ -203,14 +318,12 @@ connect_to_server(uint16_t port, uint32_t attempts, uint32_t delay) {
|
||||
}
|
||||
|
||||
static void
|
||||
close_socket(socket_t *socket) {
|
||||
assert(*socket != INVALID_SOCKET);
|
||||
net_shutdown(*socket, SHUT_RDWR);
|
||||
if (!net_close(*socket)) {
|
||||
close_socket(socket_t socket) {
|
||||
assert(socket != INVALID_SOCKET);
|
||||
net_shutdown(socket, SHUT_RDWR);
|
||||
if (!net_close(socket)) {
|
||||
LOGW("Could not close socket");
|
||||
return;
|
||||
}
|
||||
*socket = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
void
|
||||
@ -218,10 +331,26 @@ server_init(struct server *server) {
|
||||
*server = (struct server) SERVER_INITIALIZER;
|
||||
}
|
||||
|
||||
static int
|
||||
run_wait_server(void *data) {
|
||||
struct server *server = data;
|
||||
cmd_simple_wait(server->process, NULL); // ignore exit code
|
||||
// no need for synchronization, server_socket is initialized before this
|
||||
// thread was created
|
||||
if (server->server_socket != INVALID_SOCKET
|
||||
&& !atomic_flag_test_and_set(&server->server_socket_closed)) {
|
||||
// On Linux, accept() is unblocked by shutdown(), but on Windows, it is
|
||||
// unblocked by closesocket(). Therefore, call both (close_socket()).
|
||||
close_socket(server->server_socket);
|
||||
}
|
||||
LOGD("Server terminated");
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool
|
||||
server_start(struct server *server, const char *serial,
|
||||
const struct server_params *params) {
|
||||
server->local_port = params->local_port;
|
||||
server->port_range = params->port_range;
|
||||
|
||||
if (serial) {
|
||||
server->serial = SDL_strdup(serial);
|
||||
@ -231,49 +360,49 @@ server_start(struct server *server, const char *serial,
|
||||
}
|
||||
|
||||
if (!push_server(serial)) {
|
||||
SDL_free(server->serial);
|
||||
return false;
|
||||
goto error1;
|
||||
}
|
||||
|
||||
if (!enable_tunnel(server)) {
|
||||
SDL_free(server->serial);
|
||||
return false;
|
||||
}
|
||||
|
||||
// if "adb reverse" does not work (e.g. over "adb connect"), it fallbacks to
|
||||
// "adb forward", so the app socket is the client
|
||||
if (!server->tunnel_forward) {
|
||||
// At the application level, the device part is "the server" because it
|
||||
// serves video stream and control. However, at the network level, the
|
||||
// client listens and the server connects to the client. That way, the
|
||||
// client can listen before starting the server app, so there is no
|
||||
// need to try to connect until the server socket is listening on the
|
||||
// device.
|
||||
|
||||
server->server_socket = listen_on_port(params->local_port);
|
||||
if (server->server_socket == INVALID_SOCKET) {
|
||||
LOGE("Could not listen on port %" PRIu16, params->local_port);
|
||||
disable_tunnel(server);
|
||||
SDL_free(server->serial);
|
||||
return false;
|
||||
}
|
||||
if (!enable_tunnel_any_port(server, params->port_range)) {
|
||||
goto error1;
|
||||
}
|
||||
|
||||
// server will connect to our server socket
|
||||
server->process = execute_server(server, params);
|
||||
|
||||
if (server->process == PROCESS_NONE) {
|
||||
if (!server->tunnel_forward) {
|
||||
close_socket(&server->server_socket);
|
||||
goto error2;
|
||||
}
|
||||
disable_tunnel(server);
|
||||
SDL_free(server->serial);
|
||||
return false;
|
||||
|
||||
// If the server process dies before connecting to the server socket, then
|
||||
// the client will be stuck forever on accept(). To avoid the problem, we
|
||||
// must be able to wake up the accept() call when the server dies. To keep
|
||||
// things simple and multiplatform, just spawn a new thread waiting for the
|
||||
// server process and calling shutdown()/close() on the server socket if
|
||||
// necessary to wake up any accept() blocking call.
|
||||
server->wait_server_thread =
|
||||
SDL_CreateThread(run_wait_server, "wait-server", server);
|
||||
if (!server->wait_server_thread) {
|
||||
cmd_terminate(server->process);
|
||||
cmd_simple_wait(server->process, NULL); // ignore exit code
|
||||
goto error2;
|
||||
}
|
||||
|
||||
server->tunnel_enabled = true;
|
||||
|
||||
return true;
|
||||
|
||||
error2:
|
||||
if (!server->tunnel_forward) {
|
||||
bool was_closed =
|
||||
atomic_flag_test_and_set(&server->server_socket_closed);
|
||||
// the thread is not started, the flag could not be already set
|
||||
assert(!was_closed);
|
||||
close_socket(server->server_socket);
|
||||
}
|
||||
disable_tunnel(server);
|
||||
error1:
|
||||
SDL_free(server->serial);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool
|
||||
@ -291,7 +420,11 @@ server_connect_to(struct server *server) {
|
||||
}
|
||||
|
||||
// we don't need the server socket anymore
|
||||
close_socket(&server->server_socket);
|
||||
if (!atomic_flag_test_and_set(&server->server_socket_closed)) {
|
||||
// close it from here
|
||||
close_socket(server->server_socket);
|
||||
// otherwise, it is closed by run_wait_server()
|
||||
}
|
||||
} else {
|
||||
uint32_t attempts = 100;
|
||||
uint32_t delay = 100; // ms
|
||||
@ -318,29 +451,27 @@ server_connect_to(struct server *server) {
|
||||
|
||||
void
|
||||
server_stop(struct server *server) {
|
||||
if (server->server_socket != INVALID_SOCKET) {
|
||||
close_socket(&server->server_socket);
|
||||
if (server->server_socket != INVALID_SOCKET
|
||||
&& !atomic_flag_test_and_set(&server->server_socket_closed)) {
|
||||
close_socket(server->server_socket);
|
||||
}
|
||||
if (server->video_socket != INVALID_SOCKET) {
|
||||
close_socket(&server->video_socket);
|
||||
close_socket(server->video_socket);
|
||||
}
|
||||
if (server->control_socket != INVALID_SOCKET) {
|
||||
close_socket(&server->control_socket);
|
||||
close_socket(server->control_socket);
|
||||
}
|
||||
|
||||
assert(server->process != PROCESS_NONE);
|
||||
|
||||
if (!cmd_terminate(server->process)) {
|
||||
LOGW("Could not terminate server");
|
||||
}
|
||||
|
||||
cmd_simple_wait(server->process, NULL); // ignore exit code
|
||||
LOGD("Server terminated");
|
||||
cmd_terminate(server->process);
|
||||
|
||||
if (server->tunnel_enabled) {
|
||||
// ignore failure
|
||||
disable_tunnel(server);
|
||||
}
|
||||
|
||||
SDL_WaitThread(server->wait_server_thread, NULL);
|
||||
}
|
||||
|
||||
void
|
||||
|
@ -1,20 +1,26 @@
|
||||
#ifndef SERVER_H
|
||||
#define SERVER_H
|
||||
|
||||
#include <stdatomic.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <SDL2/SDL_thread.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "command.h"
|
||||
#include "common.h"
|
||||
#include "util/net.h"
|
||||
|
||||
struct server {
|
||||
char *serial;
|
||||
process_t process;
|
||||
SDL_Thread *wait_server_thread;
|
||||
atomic_flag server_socket_closed;
|
||||
socket_t server_socket; // only used if !tunnel_forward
|
||||
socket_t video_socket;
|
||||
socket_t control_socket;
|
||||
uint16_t local_port;
|
||||
struct port_range port_range;
|
||||
uint16_t local_port; // selected from port_range
|
||||
bool tunnel_enabled;
|
||||
bool tunnel_forward; // use "adb forward" instead of "adb reverse"
|
||||
};
|
||||
@ -22,9 +28,15 @@ struct server {
|
||||
#define SERVER_INITIALIZER { \
|
||||
.serial = NULL, \
|
||||
.process = PROCESS_NONE, \
|
||||
.wait_server_thread = NULL, \
|
||||
.server_socket_closed = ATOMIC_FLAG_INIT, \
|
||||
.server_socket = INVALID_SOCKET, \
|
||||
.video_socket = INVALID_SOCKET, \
|
||||
.control_socket = INVALID_SOCKET, \
|
||||
.port_range = { \
|
||||
.first = 0, \
|
||||
.last = 0, \
|
||||
}, \
|
||||
.local_port = 0, \
|
||||
.tunnel_enabled = false, \
|
||||
.tunnel_forward = false, \
|
||||
@ -32,11 +44,13 @@ struct server {
|
||||
|
||||
struct server_params {
|
||||
const char *crop;
|
||||
uint16_t local_port;
|
||||
struct port_range port_range;
|
||||
uint16_t max_size;
|
||||
uint32_t bit_rate;
|
||||
uint16_t max_fps;
|
||||
int8_t lock_video_orientation;
|
||||
bool control;
|
||||
uint16_t display_id;
|
||||
};
|
||||
|
||||
// init default values
|
||||
|
@ -14,12 +14,50 @@
|
||||
#include <limits.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "util/log.h"
|
||||
|
||||
bool
|
||||
cmd_search(const char *file) {
|
||||
char *path = getenv("PATH");
|
||||
if (!path)
|
||||
return false;
|
||||
path = strdup(path);
|
||||
if (!path)
|
||||
return false;
|
||||
|
||||
bool ret = false;
|
||||
size_t file_len = strlen(file);
|
||||
char *saveptr;
|
||||
for (char *dir = strtok_r(path, ":", &saveptr); dir;
|
||||
dir = strtok_r(NULL, ":", &saveptr)) {
|
||||
size_t dir_len = strlen(dir);
|
||||
char *fullpath = malloc(dir_len + file_len + 2);
|
||||
if (!fullpath)
|
||||
continue;
|
||||
memcpy(fullpath, dir, dir_len);
|
||||
fullpath[dir_len] = '/';
|
||||
memcpy(fullpath + dir_len + 1, file, file_len + 1);
|
||||
|
||||
struct stat sb;
|
||||
bool fullpath_executable = stat(fullpath, &sb) == 0 &&
|
||||
sb.st_mode & S_IXUSR;
|
||||
free(fullpath);
|
||||
if (fullpath_executable) {
|
||||
ret = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
free(path);
|
||||
return ret;
|
||||
}
|
||||
|
||||
enum process_result
|
||||
cmd_execute(const char *const argv[], pid_t *pid) {
|
||||
int fd[2];
|
||||
@ -127,3 +165,14 @@ get_executable_path(void) {
|
||||
return NULL;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool
|
||||
is_regular_file(const char *path) {
|
||||
struct stat path_stat;
|
||||
|
||||
if (stat(path, &path_stat)) {
|
||||
perror("stat");
|
||||
return false;
|
||||
}
|
||||
return S_ISREG(path_stat.st_mode);
|
||||
}
|
||||
|
@ -1,21 +0,0 @@
|
||||
#include "util/net.h"
|
||||
|
||||
#include <unistd.h>
|
||||
|
||||
#include "config.h"
|
||||
|
||||
bool
|
||||
net_init(void) {
|
||||
// do nothing
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
net_cleanup(void) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
bool
|
||||
net_close(socket_t socket) {
|
||||
return !close(socket);
|
||||
}
|
@ -1,5 +1,7 @@
|
||||
#include "command.h"
|
||||
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "util/log.h"
|
||||
#include "util/str_util.h"
|
||||
@ -90,3 +92,22 @@ get_executable_path(void) {
|
||||
buf[len] = '\0';
|
||||
return utf8_from_wide_char(buf);
|
||||
}
|
||||
|
||||
bool
|
||||
is_regular_file(const char *path) {
|
||||
wchar_t *wide_path = utf8_to_wide_char(path);
|
||||
if (!wide_path) {
|
||||
LOGC("Could not allocate wide char string");
|
||||
return false;
|
||||
}
|
||||
|
||||
struct _stat path_stat;
|
||||
int r = _wstat(wide_path, &path_stat);
|
||||
SDL_free(wide_path);
|
||||
|
||||
if (r) {
|
||||
perror("stat");
|
||||
return false;
|
||||
}
|
||||
return S_ISREG(path_stat.st_mode);
|
||||
}
|
||||
|
@ -1,25 +0,0 @@
|
||||
#include "util/net.h"
|
||||
|
||||
#include "config.h"
|
||||
#include "util/log.h"
|
||||
|
||||
bool
|
||||
net_init(void) {
|
||||
WSADATA wsa;
|
||||
int res = WSAStartup(MAKEWORD(2, 2), &wsa) < 0;
|
||||
if (res < 0) {
|
||||
LOGC("WSAStartup failed with error %d", res);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
net_cleanup(void) {
|
||||
WSACleanup();
|
||||
}
|
||||
|
||||
bool
|
||||
net_close(socket_t socket) {
|
||||
return !closesocket(socket);
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
#include "net.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <SDL2/SDL_platform.h>
|
||||
|
||||
#include "config.h"
|
||||
#include "log.h"
|
||||
@ -115,3 +116,32 @@ bool
|
||||
net_shutdown(socket_t socket, int how) {
|
||||
return !shutdown(socket, how);
|
||||
}
|
||||
|
||||
bool
|
||||
net_init(void) {
|
||||
#ifdef __WINDOWS__
|
||||
WSADATA wsa;
|
||||
int res = WSAStartup(MAKEWORD(2, 2), &wsa) < 0;
|
||||
if (res < 0) {
|
||||
LOGC("WSAStartup failed with error %d", res);
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
void
|
||||
net_cleanup(void) {
|
||||
#ifdef __WINDOWS__
|
||||
WSACleanup();
|
||||
#endif
|
||||
}
|
||||
|
||||
bool
|
||||
net_close(socket_t socket) {
|
||||
#ifdef __WINDOWS__
|
||||
return !closesocket(socket);
|
||||
#else
|
||||
return !close(socket);
|
||||
#endif
|
||||
}
|
||||
|
@ -81,6 +81,35 @@ parse_integer(const char *s, long *out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t
|
||||
parse_integers(const char *s, const char sep, size_t max_items, long *out) {
|
||||
size_t count = 0;
|
||||
char *endptr;
|
||||
do {
|
||||
errno = 0;
|
||||
long value = strtol(s, &endptr, 0);
|
||||
if (errno == ERANGE) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (endptr == s || (*endptr != sep && *endptr != '\0')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
out[count++] = value;
|
||||
if (*endptr == sep) {
|
||||
if (count >= max_items) {
|
||||
// max items already reached, could not accept a new item
|
||||
return 0;
|
||||
}
|
||||
// parse the next token during the next iteration
|
||||
s = endptr + 1;
|
||||
}
|
||||
} while (*endptr != '\0');
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
bool
|
||||
parse_integer_with_suffix(const char *s, long *out) {
|
||||
char *endptr;
|
||||
|
@ -31,6 +31,11 @@ strquote(const char *src);
|
||||
bool
|
||||
parse_integer(const char *s, long *out);
|
||||
|
||||
// parse s as integers separated by sep (for example '1234:2000')
|
||||
// returns the number of integers on success, 0 on failure
|
||||
size_t
|
||||
parse_integers(const char *s, const char sep, size_t max_items, long *out);
|
||||
|
||||
// parse s as an integer into value
|
||||
// like parse_integer(), but accept 'k'/'K' (x1000) and 'm'/'M' (x1000000) as
|
||||
// suffix
|
||||
|
@ -48,9 +48,10 @@ static void test_options(void) {
|
||||
"--fullscreen",
|
||||
"--max-fps", "30",
|
||||
"--max-size", "1024",
|
||||
"--lock-video-orientation", "2",
|
||||
// "--no-control" is not compatible with "--turn-screen-off"
|
||||
// "--no-display" is not compatible with "--fulscreen"
|
||||
"--port", "1234",
|
||||
"--port", "1234:1236",
|
||||
"--push-target", "/sdcard/Movies",
|
||||
"--record", "file",
|
||||
"--record-format", "mkv",
|
||||
@ -78,7 +79,9 @@ static void test_options(void) {
|
||||
assert(opts->fullscreen);
|
||||
assert(opts->max_fps == 30);
|
||||
assert(opts->max_size == 1024);
|
||||
assert(opts->port == 1234);
|
||||
assert(opts->lock_video_orientation == 2);
|
||||
assert(opts->port_range.first == 1234);
|
||||
assert(opts->port_range.last == 1236);
|
||||
assert(!strcmp(opts->push_target, "/sdcard/Movies"));
|
||||
assert(!strcmp(opts->record_filename, "file"));
|
||||
assert(opts->record_format == RECORDER_FORMAT_MKV);
|
||||
|
@ -187,6 +187,55 @@ static void test_parse_integer(void) {
|
||||
assert(!ok); // out-of-range
|
||||
}
|
||||
|
||||
static void test_parse_integers(void) {
|
||||
long values[5];
|
||||
|
||||
size_t count = parse_integers("1234", ':', 5, values);
|
||||
assert(count == 1);
|
||||
assert(values[0] == 1234);
|
||||
|
||||
count = parse_integers("1234:5678", ':', 5, values);
|
||||
assert(count == 2);
|
||||
assert(values[0] == 1234);
|
||||
assert(values[1] == 5678);
|
||||
|
||||
count = parse_integers("1234:5678", ':', 2, values);
|
||||
assert(count == 2);
|
||||
assert(values[0] == 1234);
|
||||
assert(values[1] == 5678);
|
||||
|
||||
count = parse_integers("1234:-5678", ':', 2, values);
|
||||
assert(count == 2);
|
||||
assert(values[0] == 1234);
|
||||
assert(values[1] == -5678);
|
||||
|
||||
count = parse_integers("1:2:3:4:5", ':', 5, values);
|
||||
assert(count == 5);
|
||||
assert(values[0] == 1);
|
||||
assert(values[1] == 2);
|
||||
assert(values[2] == 3);
|
||||
assert(values[3] == 4);
|
||||
assert(values[4] == 5);
|
||||
|
||||
count = parse_integers("1234:5678", ':', 1, values);
|
||||
assert(count == 0); // max_items == 1
|
||||
|
||||
count = parse_integers("1:2:3:4:5", ':', 3, values);
|
||||
assert(count == 0); // max_items == 3
|
||||
|
||||
count = parse_integers(":1234", ':', 5, values);
|
||||
assert(count == 0); // invalid
|
||||
|
||||
count = parse_integers("1234:", ':', 5, values);
|
||||
assert(count == 0); // invalid
|
||||
|
||||
count = parse_integers("1234:", ':', 1, values);
|
||||
assert(count == 0); // invalid, even when max_items == 1
|
||||
|
||||
count = parse_integers("1234::5678", ':', 5, values);
|
||||
assert(count == 0); // invalid
|
||||
}
|
||||
|
||||
static void test_parse_integer_with_suffix(void) {
|
||||
long value;
|
||||
bool ok = parse_integer_with_suffix("1234", &value);
|
||||
@ -249,6 +298,7 @@ int main(void) {
|
||||
test_strquote();
|
||||
test_utf8_truncate();
|
||||
test_parse_integer();
|
||||
test_parse_integers();
|
||||
test_parse_integer_with_suffix();
|
||||
return 0;
|
||||
}
|
||||
|
@ -129,11 +129,6 @@ page at http://checkstyle.sourceforge.net/config.html -->
|
||||
</module>
|
||||
<module name="IllegalInstantiation" />
|
||||
<module name="InnerAssignment" />
|
||||
<module name="MagicNumber">
|
||||
<property name="severity" value="info" />
|
||||
<property name="ignoreHashCodeMethod" value="true" />
|
||||
<property name="ignoreAnnotation" value="true" />
|
||||
</module>
|
||||
<module name="MissingSwitchDefault" />
|
||||
<module name="SimplifyBooleanExpression" />
|
||||
<module name="SimplifyBooleanReturn" />
|
||||
|
@ -6,3 +6,4 @@ option('prebuilt_server', type: 'string', description: 'Path of the prebuilt ser
|
||||
option('portable', type: 'boolean', value: false, description: 'Use scrcpy-server from the same directory as the scrcpy executable')
|
||||
option('hidpi_support', type: 'boolean', value: true, description: 'Enable High DPI support')
|
||||
option('server_debugger', type: 'boolean', value: false, description: 'Run a server debugger and wait for a client to be attached')
|
||||
option('server_debugger_method', type: 'combo', choices: ['old', 'new'], value: 'new', description: 'Select the debugger method (Android < 9: "old", Android >= 9: "new")')
|
||||
|
@ -8,11 +8,10 @@ import java.nio.charset.StandardCharsets;
|
||||
|
||||
public class ControlMessageReader {
|
||||
|
||||
private static final int INJECT_KEYCODE_PAYLOAD_LENGTH = 9;
|
||||
private static final int INJECT_MOUSE_EVENT_PAYLOAD_LENGTH = 17;
|
||||
private static final int INJECT_TOUCH_EVENT_PAYLOAD_LENGTH = 21;
|
||||
private static final int INJECT_SCROLL_EVENT_PAYLOAD_LENGTH = 20;
|
||||
private static final int SET_SCREEN_POWER_MODE_PAYLOAD_LENGTH = 1;
|
||||
static final int INJECT_KEYCODE_PAYLOAD_LENGTH = 9;
|
||||
static final int INJECT_TOUCH_EVENT_PAYLOAD_LENGTH = 27;
|
||||
static final int INJECT_SCROLL_EVENT_PAYLOAD_LENGTH = 20;
|
||||
static final int SET_SCREEN_POWER_MODE_PAYLOAD_LENGTH = 1;
|
||||
|
||||
public static final int TEXT_MAX_LENGTH = 300;
|
||||
public static final int CLIPBOARD_TEXT_MAX_LENGTH = 4093;
|
||||
@ -122,7 +121,6 @@ public class ControlMessageReader {
|
||||
return ControlMessage.createInjectText(text);
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private ControlMessage parseInjectTouchEvent() {
|
||||
if (buffer.remaining() < INJECT_TOUCH_EVENT_PAYLOAD_LENGTH) {
|
||||
return null;
|
||||
@ -172,12 +170,10 @@ public class ControlMessageReader {
|
||||
return new Position(x, y, screenWidth, screenHeight);
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static int toUnsigned(short value) {
|
||||
return value & 0xffff;
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static int toUnsigned(byte value) {
|
||||
return value & 0xff;
|
||||
}
|
||||
|
@ -47,7 +47,6 @@ public class Controller {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public void control() throws IOException {
|
||||
// on start, power on the device
|
||||
if (!device.isScreenOn()) {
|
||||
@ -76,19 +75,29 @@ public class Controller {
|
||||
ControlMessage msg = connection.receiveControlMessage();
|
||||
switch (msg.getType()) {
|
||||
case ControlMessage.TYPE_INJECT_KEYCODE:
|
||||
if (device.supportsInputEvents()) {
|
||||
injectKeycode(msg.getAction(), msg.getKeycode(), msg.getMetaState());
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_INJECT_TEXT:
|
||||
if (device.supportsInputEvents()) {
|
||||
injectText(msg.getText());
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_INJECT_TOUCH_EVENT:
|
||||
if (device.supportsInputEvents()) {
|
||||
injectTouch(msg.getAction(), msg.getPointerId(), msg.getPosition(), msg.getPressure(), msg.getButtons());
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_INJECT_SCROLL_EVENT:
|
||||
if (device.supportsInputEvents()) {
|
||||
injectScroll(msg.getPosition(), msg.getHScroll(), msg.getVScroll());
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_BACK_OR_SCREEN_ON:
|
||||
if (device.supportsInputEvents()) {
|
||||
pressBackOrTurnScreenOn();
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_EXPAND_NOTIFICATION_PANEL:
|
||||
device.expandNotificationPanel();
|
||||
@ -104,7 +113,9 @@ public class Controller {
|
||||
device.setClipboardText(msg.getText());
|
||||
break;
|
||||
case ControlMessage.TYPE_SET_SCREEN_POWER_MODE:
|
||||
if (device.supportsInputEvents()) {
|
||||
device.setScreenPowerMode(msg.getAction());
|
||||
}
|
||||
break;
|
||||
case ControlMessage.TYPE_ROTATE_DEVICE:
|
||||
device.rotateDevice();
|
||||
|
@ -84,7 +84,6 @@ public final class DesktopConnection implements Closeable {
|
||||
controlSocket.close();
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private void send(String deviceName, int width, int height) throws IOException {
|
||||
byte[] buffer = new byte[DEVICE_NAME_FIELD_LENGTH + 4];
|
||||
|
||||
|
@ -1,5 +1,6 @@
|
||||
package com.genymobile.scrcpy;
|
||||
|
||||
import com.genymobile.scrcpy.wrappers.InputManager;
|
||||
import com.genymobile.scrcpy.wrappers.ServiceManager;
|
||||
import com.genymobile.scrcpy.wrappers.SurfaceControl;
|
||||
import com.genymobile.scrcpy.wrappers.WindowManager;
|
||||
@ -25,13 +26,40 @@ public final class Device {
|
||||
private ScreenInfo screenInfo;
|
||||
private RotationListener rotationListener;
|
||||
|
||||
/**
|
||||
* Logical display identifier
|
||||
*/
|
||||
private final int displayId;
|
||||
|
||||
/**
|
||||
* The surface flinger layer stack associated with this logical display
|
||||
*/
|
||||
private final int layerStack;
|
||||
|
||||
/**
|
||||
* The FLAG_PRESENTATION from the DisplayInfo
|
||||
*/
|
||||
private final boolean isPresentationDisplay;
|
||||
|
||||
public Device(Options options) {
|
||||
screenInfo = computeScreenInfo(options.getCrop(), options.getMaxSize());
|
||||
displayId = options.getDisplayId();
|
||||
DisplayInfo displayInfo = serviceManager.getDisplayManager().getDisplayInfo(displayId);
|
||||
if (displayInfo == null) {
|
||||
int[] displayIds = serviceManager.getDisplayManager().getDisplayIds();
|
||||
throw new InvalidDisplayIdException(displayId, displayIds);
|
||||
}
|
||||
|
||||
int displayInfoFlags = displayInfo.getFlags();
|
||||
|
||||
screenInfo = ScreenInfo.computeScreenInfo(displayInfo, options.getCrop(), options.getMaxSize(), options.getLockedVideoOrientation());
|
||||
layerStack = displayInfo.getLayerStack();
|
||||
isPresentationDisplay = (displayInfoFlags & DisplayInfo.FLAG_PRESENTATION) != 0;
|
||||
|
||||
registerRotationWatcher(new IRotationWatcher.Stub() {
|
||||
@Override
|
||||
public void onRotationChanged(int rotation) throws RemoteException {
|
||||
synchronized (Device.this) {
|
||||
screenInfo = screenInfo.withRotation(rotation);
|
||||
screenInfo = screenInfo.withDeviceRotation(rotation);
|
||||
|
||||
// notify
|
||||
if (rotationListener != null) {
|
||||
@ -40,88 +68,69 @@ public final class Device {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if ((displayInfoFlags & DisplayInfo.FLAG_SUPPORTS_PROTECTED_BUFFERS) == 0) {
|
||||
Ln.w("Display doesn't have FLAG_SUPPORTS_PROTECTED_BUFFERS flag, mirroring can be restricted");
|
||||
}
|
||||
|
||||
if (!supportsInputEvents()) {
|
||||
Ln.w("Input events are not supported for displays with FLAG_PRESENTATION enabled for devices with API lower than 29");
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized ScreenInfo getScreenInfo() {
|
||||
return screenInfo;
|
||||
}
|
||||
|
||||
private ScreenInfo computeScreenInfo(Rect crop, int maxSize) {
|
||||
DisplayInfo displayInfo = serviceManager.getDisplayManager().getDisplayInfo();
|
||||
boolean rotated = (displayInfo.getRotation() & 1) != 0;
|
||||
Size deviceSize = displayInfo.getSize();
|
||||
Rect contentRect = new Rect(0, 0, deviceSize.getWidth(), deviceSize.getHeight());
|
||||
if (crop != null) {
|
||||
if (rotated) {
|
||||
// the crop (provided by the user) is expressed in the natural orientation
|
||||
crop = flipRect(crop);
|
||||
}
|
||||
if (!contentRect.intersect(crop)) {
|
||||
// intersect() changes contentRect so that it is intersected with crop
|
||||
Ln.w("Crop rectangle (" + formatCrop(crop) + ") does not intersect device screen (" + formatCrop(deviceSize.toRect()) + ")");
|
||||
contentRect = new Rect(); // empty
|
||||
}
|
||||
}
|
||||
|
||||
Size videoSize = computeVideoSize(contentRect.width(), contentRect.height(), maxSize);
|
||||
return new ScreenInfo(contentRect, videoSize, rotated);
|
||||
}
|
||||
|
||||
private static String formatCrop(Rect rect) {
|
||||
return rect.width() + ":" + rect.height() + ":" + rect.left + ":" + rect.top;
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static Size computeVideoSize(int w, int h, int maxSize) {
|
||||
// Compute the video size and the padding of the content inside this video.
|
||||
// Principle:
|
||||
// - scale down the great side of the screen to maxSize (if necessary);
|
||||
// - scale down the other side so that the aspect ratio is preserved;
|
||||
// - round this value to the nearest multiple of 8 (H.264 only accepts multiples of 8)
|
||||
w &= ~7; // in case it's not a multiple of 8
|
||||
h &= ~7;
|
||||
if (maxSize > 0) {
|
||||
if (BuildConfig.DEBUG && maxSize % 8 != 0) {
|
||||
throw new AssertionError("Max size must be a multiple of 8");
|
||||
}
|
||||
boolean portrait = h > w;
|
||||
int major = portrait ? h : w;
|
||||
int minor = portrait ? w : h;
|
||||
if (major > maxSize) {
|
||||
int minorExact = minor * maxSize / major;
|
||||
// +4 to round the value to the nearest multiple of 8
|
||||
minor = (minorExact + 4) & ~7;
|
||||
major = maxSize;
|
||||
}
|
||||
w = portrait ? minor : major;
|
||||
h = portrait ? major : minor;
|
||||
}
|
||||
return new Size(w, h);
|
||||
public int getLayerStack() {
|
||||
return layerStack;
|
||||
}
|
||||
|
||||
public Point getPhysicalPoint(Position position) {
|
||||
// it hides the field on purpose, to read it with a lock
|
||||
@SuppressWarnings("checkstyle:HiddenField")
|
||||
ScreenInfo screenInfo = getScreenInfo(); // read with synchronization
|
||||
Size videoSize = screenInfo.getVideoSize();
|
||||
Size clientVideoSize = position.getScreenSize();
|
||||
if (!videoSize.equals(clientVideoSize)) {
|
||||
|
||||
// ignore the locked video orientation, the events will apply in coordinates considered in the physical device orientation
|
||||
Size unlockedVideoSize = screenInfo.getUnlockedVideoSize();
|
||||
|
||||
int reverseVideoRotation = screenInfo.getReverseVideoRotation();
|
||||
// reverse the video rotation to apply the events
|
||||
Position devicePosition = position.rotate(reverseVideoRotation);
|
||||
|
||||
Size clientVideoSize = devicePosition.getScreenSize();
|
||||
if (!unlockedVideoSize.equals(clientVideoSize)) {
|
||||
// The client sends a click relative to a video with wrong dimensions,
|
||||
// the device may have been rotated since the event was generated, so ignore the event
|
||||
return null;
|
||||
}
|
||||
Rect contentRect = screenInfo.getContentRect();
|
||||
Point point = position.getPoint();
|
||||
int scaledX = contentRect.left + point.getX() * contentRect.width() / videoSize.getWidth();
|
||||
int scaledY = contentRect.top + point.getY() * contentRect.height() / videoSize.getHeight();
|
||||
return new Point(scaledX, scaledY);
|
||||
Point point = devicePosition.getPoint();
|
||||
int convertedX = contentRect.left + point.getX() * contentRect.width() / unlockedVideoSize.getWidth();
|
||||
int convertedY = contentRect.top + point.getY() * contentRect.height() / unlockedVideoSize.getHeight();
|
||||
return new Point(convertedX, convertedY);
|
||||
}
|
||||
|
||||
public static String getDeviceName() {
|
||||
return Build.MODEL;
|
||||
}
|
||||
|
||||
public boolean supportsInputEvents() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
return true;
|
||||
}
|
||||
return !isPresentationDisplay;
|
||||
}
|
||||
|
||||
public boolean injectInputEvent(InputEvent inputEvent, int mode) {
|
||||
if (!supportsInputEvents()) {
|
||||
throw new AssertionError("Could not inject input event if !supportsInputEvents()");
|
||||
}
|
||||
|
||||
if (displayId != 0 && !InputManager.setDisplayId(inputEvent, displayId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return serviceManager.getInputManager().injectInputEvent(inputEvent, mode);
|
||||
}
|
||||
|
||||
@ -154,9 +163,11 @@ public final class Device {
|
||||
}
|
||||
|
||||
public void setClipboardText(String text) {
|
||||
serviceManager.getClipboardManager().setText(text);
|
||||
boolean ok = serviceManager.getClipboardManager().setText(text);
|
||||
if (ok) {
|
||||
Ln.i("Device clipboard set");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mode one of the {@code SCREEN_POWER_MODE_*} constants
|
||||
@ -167,9 +178,11 @@ public final class Device {
|
||||
Ln.e("Could not get built-in display");
|
||||
return;
|
||||
}
|
||||
SurfaceControl.setDisplayPowerMode(d, mode);
|
||||
boolean ok = SurfaceControl.setDisplayPowerMode(d, mode);
|
||||
if (ok) {
|
||||
Ln.i("Device screen turned " + (mode == Device.POWER_MODE_OFF ? "off" : "on"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable auto-rotation (if enabled), set the screen rotation and re-enable auto-rotation (if it was enabled).
|
||||
@ -191,8 +204,4 @@ public final class Device {
|
||||
wm.thawRotation();
|
||||
}
|
||||
}
|
||||
|
||||
static Rect flipRect(Rect crop) {
|
||||
return new Rect(crop.top, crop.left, crop.bottom, crop.right);
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,6 @@ public class DeviceMessageWriter {
|
||||
private final byte[] rawBuffer = new byte[MAX_EVENT_SIZE];
|
||||
private final ByteBuffer buffer = ByteBuffer.wrap(rawBuffer);
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public void writeTo(DeviceMessage msg, OutputStream output) throws IOException {
|
||||
buffer.clear();
|
||||
buffer.put((byte) DeviceMessage.TYPE_CLIPBOARD);
|
||||
|
@ -1,12 +1,25 @@
|
||||
package com.genymobile.scrcpy;
|
||||
|
||||
public final class DisplayInfo {
|
||||
private final int displayId;
|
||||
private final Size size;
|
||||
private final int rotation;
|
||||
private final int layerStack;
|
||||
private final int flags;
|
||||
|
||||
public DisplayInfo(Size size, int rotation) {
|
||||
public static final int FLAG_SUPPORTS_PROTECTED_BUFFERS = 0x00000001;
|
||||
public static final int FLAG_PRESENTATION = 0x00000008;
|
||||
|
||||
public DisplayInfo(int displayId, Size size, int rotation, int layerStack, int flags) {
|
||||
this.displayId = displayId;
|
||||
this.size = size;
|
||||
this.rotation = rotation;
|
||||
this.layerStack = layerStack;
|
||||
this.flags = flags;
|
||||
}
|
||||
|
||||
public int getDisplayId() {
|
||||
return displayId;
|
||||
}
|
||||
|
||||
public Size getSize() {
|
||||
@ -16,5 +29,13 @@ public final class DisplayInfo {
|
||||
public int getRotation() {
|
||||
return rotation;
|
||||
}
|
||||
|
||||
public int getLayerStack() {
|
||||
return layerStack;
|
||||
}
|
||||
|
||||
public int getFlags() {
|
||||
return flags;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -0,0 +1,21 @@
|
||||
package com.genymobile.scrcpy;
|
||||
|
||||
public class InvalidDisplayIdException extends RuntimeException {
|
||||
|
||||
private final int displayId;
|
||||
private final int[] availableDisplayIds;
|
||||
|
||||
public InvalidDisplayIdException(int displayId, int[] availableDisplayIds) {
|
||||
super("There is no display having id " + displayId);
|
||||
this.displayId = displayId;
|
||||
this.availableDisplayIds = availableDisplayIds;
|
||||
}
|
||||
|
||||
public int getDisplayId() {
|
||||
return displayId;
|
||||
}
|
||||
|
||||
public int[] getAvailableDisplayIds() {
|
||||
return availableDisplayIds;
|
||||
}
|
||||
}
|
@ -6,10 +6,12 @@ public class Options {
|
||||
private int maxSize;
|
||||
private int bitRate;
|
||||
private int maxFps;
|
||||
private int lockedVideoOrientation;
|
||||
private boolean tunnelForward;
|
||||
private Rect crop;
|
||||
private boolean sendFrameMeta; // send PTS so that the client may record properly
|
||||
private boolean control;
|
||||
private int displayId;
|
||||
|
||||
public int getMaxSize() {
|
||||
return maxSize;
|
||||
@ -35,6 +37,14 @@ public class Options {
|
||||
this.maxFps = maxFps;
|
||||
}
|
||||
|
||||
public int getLockedVideoOrientation() {
|
||||
return lockedVideoOrientation;
|
||||
}
|
||||
|
||||
public void setLockedVideoOrientation(int lockedVideoOrientation) {
|
||||
this.lockedVideoOrientation = lockedVideoOrientation;
|
||||
}
|
||||
|
||||
public boolean isTunnelForward() {
|
||||
return tunnelForward;
|
||||
}
|
||||
@ -66,4 +76,12 @@ public class Options {
|
||||
public void setControl(boolean control) {
|
||||
this.control = control;
|
||||
}
|
||||
|
||||
public int getDisplayId() {
|
||||
return displayId;
|
||||
}
|
||||
|
||||
public void setDisplayId(int displayId) {
|
||||
this.displayId = displayId;
|
||||
}
|
||||
}
|
||||
|
@ -23,6 +23,19 @@ public class Position {
|
||||
return screenSize;
|
||||
}
|
||||
|
||||
public Position rotate(int rotation) {
|
||||
switch (rotation) {
|
||||
case 1:
|
||||
return new Position(new Point(screenSize.getHeight() - point.getY(), point.getX()), screenSize.rotate());
|
||||
case 2:
|
||||
return new Position(new Point(screenSize.getWidth() - point.getX(), screenSize.getHeight() - point.getY()), screenSize);
|
||||
case 3:
|
||||
return new Position(new Point(point.getY(), screenSize.getWidth() - point.getX()), screenSize.rotate());
|
||||
default:
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
|
@ -6,7 +6,6 @@ import android.graphics.Rect;
|
||||
import android.media.MediaCodec;
|
||||
import android.media.MediaCodecInfo;
|
||||
import android.media.MediaFormat;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import android.view.Surface;
|
||||
|
||||
@ -19,6 +18,7 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
|
||||
private static final int DEFAULT_I_FRAME_INTERVAL = 10; // seconds
|
||||
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;
|
||||
|
||||
@ -27,19 +27,21 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
|
||||
private int bitRate;
|
||||
private int maxFps;
|
||||
private int lockedVideoOrientation;
|
||||
private int iFrameInterval;
|
||||
private boolean sendFrameMeta;
|
||||
private long ptsOrigin;
|
||||
|
||||
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps, int iFrameInterval) {
|
||||
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps, int lockedVideoOrientation, int iFrameInterval) {
|
||||
this.sendFrameMeta = sendFrameMeta;
|
||||
this.bitRate = bitRate;
|
||||
this.maxFps = maxFps;
|
||||
this.lockedVideoOrientation = lockedVideoOrientation;
|
||||
this.iFrameInterval = iFrameInterval;
|
||||
}
|
||||
|
||||
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps) {
|
||||
this(sendFrameMeta, bitRate, maxFps, DEFAULT_I_FRAME_INTERVAL);
|
||||
public ScreenEncoder(boolean sendFrameMeta, int bitRate, int maxFps, int lockedVideoOrientation) {
|
||||
this(sendFrameMeta, bitRate, maxFps, lockedVideoOrientation, DEFAULT_I_FRAME_INTERVAL);
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -62,12 +64,19 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
do {
|
||||
MediaCodec codec = createCodec();
|
||||
IBinder display = createDisplay();
|
||||
Rect contentRect = device.getScreenInfo().getContentRect();
|
||||
Rect videoRect = device.getScreenInfo().getVideoSize().toRect();
|
||||
ScreenInfo screenInfo = device.getScreenInfo();
|
||||
Rect contentRect = screenInfo.getContentRect();
|
||||
// include the locked video orientation
|
||||
Rect videoRect = screenInfo.getVideoSize().toRect();
|
||||
// does not include the locked video orientation
|
||||
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, contentRect, videoRect);
|
||||
setDisplaySurface(display, surface, videoRotation, contentRect, unlockedVideoRect, layerStack);
|
||||
codec.start();
|
||||
try {
|
||||
alive = encode(codec, fd);
|
||||
@ -138,7 +147,6 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
return MediaCodec.createEncoderByType("video/avc");
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static MediaFormat createFormat(int bitRate, int maxFps, int iFrameInterval) {
|
||||
MediaFormat format = new MediaFormat();
|
||||
format.setString(MediaFormat.KEY_MIME, "video/avc");
|
||||
@ -150,11 +158,10 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
// display the very first frame, and recover from bad quality when no new frames
|
||||
format.setLong(MediaFormat.KEY_REPEAT_PREVIOUS_FRAME_AFTER, REPEAT_FRAME_DELAY_US); // µs
|
||||
if (maxFps > 0) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
format.setFloat(MediaFormat.KEY_MAX_FPS_TO_ENCODER, maxFps);
|
||||
} else {
|
||||
Ln.w("Max FPS is only supported since Android 10, the option has been ignored");
|
||||
}
|
||||
// The key existed privately before Android 10:
|
||||
// <https://android.googlesource.com/platform/frameworks/base/+/625f0aad9f7a259b6881006ad8710adce57d1384%5E%21/>
|
||||
// <https://github.com/Genymobile/scrcpy/issues/488#issuecomment-567321437>
|
||||
format.setFloat(KEY_MAX_FPS_TO_ENCODER, maxFps);
|
||||
}
|
||||
return format;
|
||||
}
|
||||
@ -172,12 +179,12 @@ public class ScreenEncoder implements Device.RotationListener {
|
||||
format.setInteger(MediaFormat.KEY_HEIGHT, height);
|
||||
}
|
||||
|
||||
private static void setDisplaySurface(IBinder display, Surface surface, Rect deviceRect, Rect displayRect) {
|
||||
private static void setDisplaySurface(IBinder display, Surface surface, int orientation, Rect deviceRect, Rect displayRect, int layerStack) {
|
||||
SurfaceControl.openTransaction();
|
||||
try {
|
||||
SurfaceControl.setDisplaySurface(display, surface);
|
||||
SurfaceControl.setDisplayProjection(display, 0, deviceRect, displayRect);
|
||||
SurfaceControl.setDisplayLayerStack(display, 0);
|
||||
SurfaceControl.setDisplayProjection(display, orientation, deviceRect, displayRect);
|
||||
SurfaceControl.setDisplayLayerStack(display, layerStack);
|
||||
} finally {
|
||||
SurfaceControl.closeTransaction();
|
||||
}
|
||||
|
@ -3,29 +3,161 @@ package com.genymobile.scrcpy;
|
||||
import android.graphics.Rect;
|
||||
|
||||
public final class ScreenInfo {
|
||||
/**
|
||||
* Device (physical) size, possibly cropped
|
||||
*/
|
||||
private final Rect contentRect; // device size, possibly cropped
|
||||
private final Size videoSize;
|
||||
private final boolean rotated;
|
||||
|
||||
public ScreenInfo(Rect contentRect, Size videoSize, boolean rotated) {
|
||||
/**
|
||||
* Video size, possibly smaller than the device size, already taking the device rotation and crop into account.
|
||||
* <p>
|
||||
* However, it does not include the locked video orientation.
|
||||
*/
|
||||
private final Size unlockedVideoSize;
|
||||
|
||||
/**
|
||||
* Device rotation, related to the natural device orientation (0, 1, 2 or 3)
|
||||
*/
|
||||
private final int deviceRotation;
|
||||
|
||||
/**
|
||||
* The locked video orientation (-1: disabled, 0: normal, 1: 90° CCW, 2: 180°, 3: 90° CW)
|
||||
*/
|
||||
private final int lockedVideoOrientation;
|
||||
|
||||
public ScreenInfo(Rect contentRect, Size unlockedVideoSize, int deviceRotation, int lockedVideoOrientation) {
|
||||
this.contentRect = contentRect;
|
||||
this.videoSize = videoSize;
|
||||
this.rotated = rotated;
|
||||
this.unlockedVideoSize = unlockedVideoSize;
|
||||
this.deviceRotation = deviceRotation;
|
||||
this.lockedVideoOrientation = lockedVideoOrientation;
|
||||
}
|
||||
|
||||
public Rect getContentRect() {
|
||||
return contentRect;
|
||||
}
|
||||
|
||||
public Size getVideoSize() {
|
||||
return videoSize;
|
||||
/**
|
||||
* Return the video size as if locked video orientation was not set.
|
||||
*
|
||||
* @return the unlocked video size
|
||||
*/
|
||||
public Size getUnlockedVideoSize() {
|
||||
return unlockedVideoSize;
|
||||
}
|
||||
|
||||
public ScreenInfo withRotation(int rotation) {
|
||||
boolean newRotated = (rotation & 1) != 0;
|
||||
if (rotated == newRotated) {
|
||||
/**
|
||||
* Return the actual video size if locked video orientation is set.
|
||||
*
|
||||
* @return the actual video size
|
||||
*/
|
||||
public Size getVideoSize() {
|
||||
if (getVideoRotation() % 2 == 0) {
|
||||
return unlockedVideoSize;
|
||||
}
|
||||
|
||||
return unlockedVideoSize.rotate();
|
||||
}
|
||||
|
||||
public int getDeviceRotation() {
|
||||
return deviceRotation;
|
||||
}
|
||||
|
||||
public ScreenInfo withDeviceRotation(int newDeviceRotation) {
|
||||
if (newDeviceRotation == deviceRotation) {
|
||||
return this;
|
||||
}
|
||||
return new ScreenInfo(Device.flipRect(contentRect), videoSize.rotate(), newRotated);
|
||||
// true if changed between portrait and landscape
|
||||
boolean orientationChanged = (deviceRotation + newDeviceRotation) % 2 != 0;
|
||||
Rect newContentRect;
|
||||
Size newUnlockedVideoSize;
|
||||
if (orientationChanged) {
|
||||
newContentRect = flipRect(contentRect);
|
||||
newUnlockedVideoSize = unlockedVideoSize.rotate();
|
||||
} else {
|
||||
newContentRect = contentRect;
|
||||
newUnlockedVideoSize = unlockedVideoSize;
|
||||
}
|
||||
return new ScreenInfo(newContentRect, newUnlockedVideoSize, newDeviceRotation, lockedVideoOrientation);
|
||||
}
|
||||
|
||||
public static ScreenInfo computeScreenInfo(DisplayInfo displayInfo, Rect crop, int maxSize, int lockedVideoOrientation) {
|
||||
int rotation = displayInfo.getRotation();
|
||||
Size deviceSize = displayInfo.getSize();
|
||||
Rect contentRect = new Rect(0, 0, deviceSize.getWidth(), deviceSize.getHeight());
|
||||
if (crop != null) {
|
||||
if (rotation % 2 != 0) { // 180s preserve dimensions
|
||||
// the crop (provided by the user) is expressed in the natural orientation
|
||||
crop = flipRect(crop);
|
||||
}
|
||||
if (!contentRect.intersect(crop)) {
|
||||
// intersect() changes contentRect so that it is intersected with crop
|
||||
Ln.w("Crop rectangle (" + formatCrop(crop) + ") does not intersect device screen (" + formatCrop(deviceSize.toRect()) + ")");
|
||||
contentRect = new Rect(); // empty
|
||||
}
|
||||
}
|
||||
|
||||
Size videoSize = computeVideoSize(contentRect.width(), contentRect.height(), maxSize);
|
||||
return new ScreenInfo(contentRect, videoSize, rotation, lockedVideoOrientation);
|
||||
}
|
||||
|
||||
private static String formatCrop(Rect rect) {
|
||||
return rect.width() + ":" + rect.height() + ":" + rect.left + ":" + rect.top;
|
||||
}
|
||||
|
||||
private static Size computeVideoSize(int w, int h, int maxSize) {
|
||||
// Compute the video size and the padding of the content inside this video.
|
||||
// Principle:
|
||||
// - scale down the great side of the screen to maxSize (if necessary);
|
||||
// - scale down the other side so that the aspect ratio is preserved;
|
||||
// - round this value to the nearest multiple of 8 (H.264 only accepts multiples of 8)
|
||||
w &= ~7; // in case it's not a multiple of 8
|
||||
h &= ~7;
|
||||
if (maxSize > 0) {
|
||||
if (BuildConfig.DEBUG && maxSize % 8 != 0) {
|
||||
throw new AssertionError("Max size must be a multiple of 8");
|
||||
}
|
||||
boolean portrait = h > w;
|
||||
int major = portrait ? h : w;
|
||||
int minor = portrait ? w : h;
|
||||
if (major > maxSize) {
|
||||
int minorExact = minor * maxSize / major;
|
||||
// +4 to round the value to the nearest multiple of 8
|
||||
minor = (minorExact + 4) & ~7;
|
||||
major = maxSize;
|
||||
}
|
||||
w = portrait ? minor : major;
|
||||
h = portrait ? major : minor;
|
||||
}
|
||||
return new Size(w, h);
|
||||
}
|
||||
|
||||
private static Rect flipRect(Rect crop) {
|
||||
return new Rect(crop.top, crop.left, crop.bottom, crop.right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the rotation to apply to the device rotation to get the requested locked video orientation
|
||||
*
|
||||
* @return the rotation offset
|
||||
*/
|
||||
public int getVideoRotation() {
|
||||
if (lockedVideoOrientation == -1) {
|
||||
// no offset
|
||||
return 0;
|
||||
}
|
||||
return (deviceRotation + 4 - lockedVideoOrientation) % 4;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the rotation to apply to the requested locked video orientation to get the device rotation
|
||||
*
|
||||
* @return the (reverse) rotation offset
|
||||
*/
|
||||
public int getReverseVideoRotation() {
|
||||
if (lockedVideoOrientation == -1) {
|
||||
// no offset
|
||||
return 0;
|
||||
}
|
||||
return (lockedVideoOrientation + 4 - deviceRotation) % 4;
|
||||
}
|
||||
}
|
||||
|
@ -16,10 +16,12 @@ public final class Server {
|
||||
}
|
||||
|
||||
private static void scrcpy(Options options) throws IOException {
|
||||
Ln.i("Device: " + Build.MANUFACTURER + " " + Build.MODEL + " (Android " + Build.VERSION.RELEASE + ")");
|
||||
final Device device = new Device(options);
|
||||
boolean tunnelForward = options.isTunnelForward();
|
||||
try (DesktopConnection connection = DesktopConnection.open(device, tunnelForward)) {
|
||||
ScreenEncoder screenEncoder = new ScreenEncoder(options.getSendFrameMeta(), options.getBitRate(), options.getMaxFps());
|
||||
ScreenEncoder screenEncoder = new ScreenEncoder(options.getSendFrameMeta(), options.getBitRate(), options.getMaxFps(),
|
||||
options.getLockedVideoOrientation());
|
||||
|
||||
if (options.getControl()) {
|
||||
Controller controller = new Controller(device, connection);
|
||||
@ -67,7 +69,6 @@ public final class Server {
|
||||
}).start();
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static Options createOptions(String... args) {
|
||||
if (args.length < 1) {
|
||||
throw new IllegalArgumentException("Missing client version");
|
||||
@ -76,11 +77,11 @@ public final class Server {
|
||||
String clientVersion = args[0];
|
||||
if (!clientVersion.equals(BuildConfig.VERSION_NAME)) {
|
||||
throw new IllegalArgumentException(
|
||||
"The server version (" + clientVersion + ") does not match the client " + "(" + BuildConfig.VERSION_NAME + ")");
|
||||
"The server version (" + BuildConfig.VERSION_NAME + ") does not match the client " + "(" + clientVersion + ")");
|
||||
}
|
||||
|
||||
if (args.length != 8) {
|
||||
throw new IllegalArgumentException("Expecting 8 parameters");
|
||||
if (args.length != 10) {
|
||||
throw new IllegalArgumentException("Expecting 10 parameters");
|
||||
}
|
||||
|
||||
Options options = new Options();
|
||||
@ -94,23 +95,28 @@ public final class Server {
|
||||
int maxFps = Integer.parseInt(args[3]);
|
||||
options.setMaxFps(maxFps);
|
||||
|
||||
int lockedVideoOrientation = Integer.parseInt(args[4]);
|
||||
options.setLockedVideoOrientation(lockedVideoOrientation);
|
||||
|
||||
// use "adb forward" instead of "adb tunnel"? (so the server must listen)
|
||||
boolean tunnelForward = Boolean.parseBoolean(args[4]);
|
||||
boolean tunnelForward = Boolean.parseBoolean(args[5]);
|
||||
options.setTunnelForward(tunnelForward);
|
||||
|
||||
Rect crop = parseCrop(args[5]);
|
||||
Rect crop = parseCrop(args[6]);
|
||||
options.setCrop(crop);
|
||||
|
||||
boolean sendFrameMeta = Boolean.parseBoolean(args[6]);
|
||||
boolean sendFrameMeta = Boolean.parseBoolean(args[7]);
|
||||
options.setSendFrameMeta(sendFrameMeta);
|
||||
|
||||
boolean control = Boolean.parseBoolean(args[7]);
|
||||
boolean control = Boolean.parseBoolean(args[8]);
|
||||
options.setControl(control);
|
||||
|
||||
int displayId = Integer.parseInt(args[9]);
|
||||
options.setDisplayId(displayId);
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static Rect parseCrop(String crop) {
|
||||
if ("-".equals(crop)) {
|
||||
return null;
|
||||
@ -135,7 +141,6 @@ public final class Server {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
private static void suggestFix(Throwable e) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||
if (e instanceof MediaCodec.CodecException) {
|
||||
@ -147,6 +152,16 @@ public final class Server {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (e instanceof InvalidDisplayIdException) {
|
||||
InvalidDisplayIdException idie = (InvalidDisplayIdException) e;
|
||||
int[] displayIds = idie.getAvailableDisplayIds();
|
||||
if (displayIds != null && displayIds.length > 0) {
|
||||
Ln.e("Try to use one of the available display ids:");
|
||||
for (int id : displayIds) {
|
||||
Ln.e(" scrcpy --display " + id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String... args) throws Exception {
|
||||
|
@ -5,7 +5,6 @@ public final class StringUtils {
|
||||
// not instantiable
|
||||
}
|
||||
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public static int getUtf8TruncationIndex(byte[] utf8, int maxLength) {
|
||||
int len = utf8.length;
|
||||
if (len <= maxLength) {
|
||||
|
@ -73,7 +73,7 @@ public final class Workarounds {
|
||||
mInitialApplicationField.set(activityThread, app);
|
||||
} catch (Throwable throwable) {
|
||||
// this is a workaround, so failing is not an error
|
||||
Ln.w("Could not fill app info: " + throwable.getMessage());
|
||||
Ln.d("Could not fill app info: " + throwable.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -74,13 +74,15 @@ public class ClipboardManager {
|
||||
}
|
||||
}
|
||||
|
||||
public void setText(CharSequence text) {
|
||||
public boolean setText(CharSequence text) {
|
||||
try {
|
||||
Method method = getSetPrimaryClipMethod();
|
||||
ClipData clipData = ClipData.newPlainText(null, text);
|
||||
setPrimaryClip(method, manager, clipData);
|
||||
return true;
|
||||
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
|
||||
Ln.e("Could not invoke method", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,15 +12,28 @@ public final class DisplayManager {
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
public DisplayInfo getDisplayInfo() {
|
||||
public DisplayInfo getDisplayInfo(int displayId) {
|
||||
try {
|
||||
Object displayInfo = manager.getClass().getMethod("getDisplayInfo", int.class).invoke(manager, 0);
|
||||
Object displayInfo = manager.getClass().getMethod("getDisplayInfo", int.class).invoke(manager, displayId);
|
||||
if (displayInfo == null) {
|
||||
return null;
|
||||
}
|
||||
Class<?> cls = displayInfo.getClass();
|
||||
// width and height already take the rotation into account
|
||||
int width = cls.getDeclaredField("logicalWidth").getInt(displayInfo);
|
||||
int height = cls.getDeclaredField("logicalHeight").getInt(displayInfo);
|
||||
int rotation = cls.getDeclaredField("rotation").getInt(displayInfo);
|
||||
return new DisplayInfo(new Size(width, height), rotation);
|
||||
int layerStack = cls.getDeclaredField("layerStack").getInt(displayInfo);
|
||||
int flags = cls.getDeclaredField("flags").getInt(displayInfo);
|
||||
return new DisplayInfo(displayId, new Size(width, height), rotation, layerStack, flags);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public int[] getDisplayIds() {
|
||||
try {
|
||||
return (int[]) manager.getClass().getMethod("getDisplayIds").invoke(manager);
|
||||
} catch (Exception e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
|
@ -17,6 +17,8 @@ public final class InputManager {
|
||||
private final IInterface manager;
|
||||
private Method injectInputEventMethod;
|
||||
|
||||
private static Method setDisplayIdMethod;
|
||||
|
||||
public InputManager(IInterface manager) {
|
||||
this.manager = manager;
|
||||
}
|
||||
@ -37,4 +39,23 @@ public final class InputManager {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Method getSetDisplayIdMethod() throws NoSuchMethodException {
|
||||
if (setDisplayIdMethod == null) {
|
||||
setDisplayIdMethod = InputEvent.class.getMethod("setDisplayId", int.class);
|
||||
}
|
||||
return setDisplayIdMethod;
|
||||
}
|
||||
|
||||
public static boolean setDisplayId(InputEvent inputEvent, int displayId) {
|
||||
try {
|
||||
Method method = getSetDisplayIdMethod();
|
||||
method.invoke(inputEvent, displayId);
|
||||
return true;
|
||||
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
|
||||
// just a warning, it might happen on old devices
|
||||
Ln.w("Cannot associate a display id to the input event");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -121,12 +121,14 @@ public final class SurfaceControl {
|
||||
return setDisplayPowerModeMethod;
|
||||
}
|
||||
|
||||
public static void setDisplayPowerMode(IBinder displayToken, int mode) {
|
||||
public static boolean setDisplayPowerMode(IBinder displayToken, int mode) {
|
||||
try {
|
||||
Method method = getSetDisplayPowerModeMethod();
|
||||
method.invoke(null, displayToken, mode);
|
||||
return true;
|
||||
} catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException e) {
|
||||
Ln.e("Could not invoke method", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -28,6 +28,9 @@ public class ControlMessageReaderTest {
|
||||
dos.writeInt(KeyEvent.META_CTRL_ON);
|
||||
byte[] packet = bos.toByteArray();
|
||||
|
||||
// The message type (1 byte) does not count
|
||||
Assert.assertEquals(ControlMessageReader.INJECT_KEYCODE_PAYLOAD_LENGTH, packet.length - 1);
|
||||
|
||||
reader.readFrom(new ByteArrayInputStream(packet));
|
||||
ControlMessage event = reader.next();
|
||||
|
||||
@ -77,7 +80,6 @@ public class ControlMessageReaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public void testParseTouchEvent() throws IOException {
|
||||
ControlMessageReader reader = new ControlMessageReader();
|
||||
|
||||
@ -95,6 +97,9 @@ public class ControlMessageReaderTest {
|
||||
|
||||
byte[] packet = bos.toByteArray();
|
||||
|
||||
// The message type (1 byte) does not count
|
||||
Assert.assertEquals(ControlMessageReader.INJECT_TOUCH_EVENT_PAYLOAD_LENGTH, packet.length - 1);
|
||||
|
||||
reader.readFrom(new ByteArrayInputStream(packet));
|
||||
ControlMessage event = reader.next();
|
||||
|
||||
@ -110,7 +115,6 @@ public class ControlMessageReaderTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public void testParseScrollEvent() throws IOException {
|
||||
ControlMessageReader reader = new ControlMessageReader();
|
||||
|
||||
@ -126,6 +130,9 @@ public class ControlMessageReaderTest {
|
||||
|
||||
byte[] packet = bos.toByteArray();
|
||||
|
||||
// The message type (1 byte) does not count
|
||||
Assert.assertEquals(ControlMessageReader.INJECT_SCROLL_EVENT_PAYLOAD_LENGTH, packet.length - 1);
|
||||
|
||||
reader.readFrom(new ByteArrayInputStream(packet));
|
||||
ControlMessage event = reader.next();
|
||||
|
||||
@ -233,6 +240,9 @@ public class ControlMessageReaderTest {
|
||||
|
||||
byte[] packet = bos.toByteArray();
|
||||
|
||||
// The message type (1 byte) does not count
|
||||
Assert.assertEquals(ControlMessageReader.SET_SCREEN_POWER_MODE_PAYLOAD_LENGTH, packet.length - 1);
|
||||
|
||||
reader.readFrom(new ByteArrayInputStream(packet));
|
||||
ControlMessage event = reader.next();
|
||||
|
||||
|
@ -8,7 +8,6 @@ import java.nio.charset.StandardCharsets;
|
||||
public class StringUtilsTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("checkstyle:MagicNumber")
|
||||
public void testUtf8Truncate() {
|
||||
String s = "aÉbÔc";
|
||||
byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
|
||||
|
Reference in New Issue
Block a user