Commit Graph

1540 Commits (master)

Author SHA1 Message Date
Romain Vimont 1846d2f078 Prevent killing unexpected process
A missing initialization (fixed by the previous commit) leaded to kill
unexpected process.

In order to prevent consequences of similar errors in the future, never
call kill() with a non-positive PID.

See <https://github.com/Genymobile/scrcpy/issues/182>.
6 years ago
Romain Vimont 1a0139321b Fix missing installer initialization
The current_process field of struct installer was not initialized.
Since the installer instance is static, its default value was 0.

The call to installer_stop() then called kill(0, SIGTERM) (on Linux),
which sent SIGTERM to every process in the process group. In particular,
the scrcpy process was killed.

As a consequence, the last cleanup steps, like disabling "show touches",
were not executed.

Fixes <https://github.com/Genymobile/scrcpy/issues/183>.
6 years ago
Romain Vimont f705a73149 Use a meson option to crossbuild for Windows
Meson decided to crossbuild for Windows as soon as
meson.is_cross_build() returned true. This made non-Windows crossbuilds
fail.

Instead, add an explicit option "crossbuild_windows".

Fixes <https://github.com/Genymobile/scrcpy/issues/165>.
6 years ago
Romain Vimont 8106bb8215 Bump version to 1.2 6 years ago
Romain Vimont a63dd47f2d Make CreateProcess() flags depend on "noconsole"
On Windows, display the output of external commands (adb) when a console
is available.
6 years ago
Romain Vimont aedc2c2da9 Also build "noconsole" binary for Windows
On Windows, an application is either console or gui, it cannot be both.

Scrcpy should be both: it outputs important information to console, but
we still want to be able to ignore the console and launch it without a
visible cmd.exe window.

Therefore, build two binaries:
 - scrcpy.exe
 - scrcpy-noconsole.exe
6 years ago
Romain Vimont 106b87a4d2 Add cross-compilation scripts for Windows
Build the Windows binary from mingw on Linux, using the official
prebuilt binaries for ffmpeg, SDL2 and adb.

MSYS2 and all its packaged dll are not necessary anymore.
6 years ago
Romain Vimont 6274cc3767 Document APK drag & drop
Add the drag & drop shortcut for installing an APK file to the README
and the help.
6 years ago
Romain Vimont 9c6f9b24f9 Quote apk path on Windows
Windows will parse the string, so the local name must be quoted.
6 years ago
Adonis Najimi e2a2973990 Drag and drop to install apk files from computer
<https://github.com/Genymobile/scrcpy/pull/133>
6 years ago
Romain Vimont 41419a2e77 Fix net_send_all() warning
If len is not positive, w could be returned uninitialized.
6 years ago
Romain Vimont e3d0a59c80 Fix proc_show_touches warning
In practice, proc_show_touches may not be used uninitialized, since it
checks the flag options->show_touches, but the compiler can't know that,
so initialize it to avoid the warning.
6 years ago
Romain Vimont bb3a7f05ac Release controller lock while processing events
Once the controller took a control event, release the mutex before
processing it, so that the main thread is not blocked to push a new
event.
6 years ago
Romain Vimont ec02823045 Fix leak on server start error
Fail on SDL_strdup() failure, and free the duplicated serial on further
error.
6 years ago
Romain Vimont 435a7fe314 Add missing includes
Include string.h and stdio.h explicitly.
6 years ago
Romain Vimont 78da66f126 Merge branch 'master' into dev 6 years ago
Romain Vimont 9aa88b6fc3 Map numpad ENTER key
Forward numpad ENTER key to the device.

Fixes <https://github.com/Genymobile/scrcpy/issues/117>.
6 years ago
Romain Vimont 0871bca9c7 Avoid pointer arithmetic on "void *"
Fix the following warning (with -Wpedantic enabled):

    pointer of type ‘void *’ used in arithmetic [-Wpointer-arith]
6 years ago
Romain Vimont b2b5404883 Use const pointers when possible
Sending data only require to read the input buffer, so declare it const.
6 years ago
Romain Vimont 1bddb80b5f Change volume shortcuts
I could not make Ctrl+'+' and Ctrl+'-' work for every keyboard on every
platform.

Instead, use Ctrl+UP and Ctrl+DOWN (like in VLC) to change the volume.

Fixes <https://github.com/Genymobile/scrcpy/issues/103>.
6 years ago
Romain Vimont 71f50fb697 Merge branch 'master' into dev 6 years ago
Romain Vimont 82efff34e8 Factorize texture creation
SDL_CreateTexture() is called both during initialization and on frame
size change.

To avoid inconsistent changes to arguments value, factorize them to a
single function create_texture().
6 years ago
Romain Vimont 860006e082 Forward double-click events
Double-clicks were not sent to the device anymore since the
"double-click on black borders" feature.

When a double click occurs inside the device screen, send the event to
the device normally.

Fixes <https://github.com/Genymobile/scrcpy/issues/97>.
6 years ago
Romain Vimont 57eaf05289 Improve startup time when show_touches is enabled
Enabling "show touches" involves the execution of an adb command, which
takes some time.

In order to parallelize, execute the command as soon as possible, but
reap the process only once everything is initialized.
6 years ago
Romain Vimont dd2a5c1ecf Disable "show touches" once window is closed
If --show-touches is set, then the option must be disabled on quit.

Since it executes an adb command, it takes some time, so close the
window beforehand so that the close window button does not seem
unresponsive.
6 years ago
Romain Vimont 66ec252893 Add an option to enable "show touches"
Add -t/--show-touches option to show physical touches while scrcpy is
running.

See <https://github.com/Genymobile/scrcpy/issues/96>.
6 years ago
Romain Vimont b13d25b9f4 Group scrcpy options into a struct
The scrcpy() function accepts as many parameters as there are options.

To simplify, group all options in a separate struct.
6 years ago
Romain Vimont b449c09442 Merge branch 'master' into dev 6 years ago
Romain Vimont 35298bb0c6 Process the last video frame
On H.264 stream EOF, the eof_reached flag is set, but av_read_frame()
still provides a frame, so check the flag only afterwards.

As a side-effect, it also fixes a memory leak (the very last packet was
not unref).
6 years ago
Romain Vimont 73c332e3e4 Unref last packet on exit 6 years ago
Romain Vimont 29b5c5b8f4 Merge branch 'arich/addShake' into dev (#85)
Add support for CTRL+S to send hardware "shake" to device
6 years ago
Romain Vimont 88ee6bc928 Swap MENU and APP_SWITCH shortcuts
Ctrl+s was mapped to MENU, while Ctrl+m was mapped to APP_SWITCH.

To avoid confusion, swap the shortcuts:
 - Ctrl+m like _M_enu
 - Ctrl+s like _S_witch
6 years ago
Romain Vimont 35e9a64c34 Rename "shake" to "menu"
The action sends AKEYCODE_MENU, so just name it "menu".

See <https://github.com/Genymobile/scrcpy/pull/85>.
6 years ago
Andy Rich 301c52b603 Add support for CTRL+S to send hardware "shake" to device w/readme 6 years ago
Romain Vimont f00c6c5b13 Disable custom SDL signal handlers
Request SDL not to replace the SIGINT and SIGTERM handlers, so that the
process is immediately terminated on Ctrl+C.

This avoids process hanging on Ctrl+C during network calls on
initialization.

Some of them accepted a timeout, but it was not used since
commit 9b056f5091 anymore.
6 years ago
Romain Vimont 3b3803da0d Remove useless blocks in switch/case
Remove unnecessary additional blocks.
6 years ago
Romain Vimont f5cf6c1b2c Include source root directory
All headers and sources are in src/. To avoid using relative includes
from subdirectories ("../../"), include the source root directory.
6 years ago
Romain Vimont c65cb36d3b Increase the number of connection attempts
In "adb forward" mode, it may take a while before the server socket is
listening, so increase the number of connection attempts.

See <https://github.com/Genymobile/scrcpy/issues/5#issuecomment-373718551>.
6 years ago
Romain Vimont 821ec9843c Fix win32 build
The types size_t and ssize_t are defined on Windows (in MSYS2), so there
is no need to typedef SIZE_T and SSIZE_T.

Exit code is "unsigned long" both on Windows 32 and 64 bits.

See <https://github.com/Genymobile/scrcpy/issues/46#issuecomment-373603596>.
6 years ago
Romain Vimont f16bd88802 Remove useless cast
For consistency with mouse button events handling, directly assign from
Sint32 to Uint16.
6 years ago
Romain Vimont f3e8834a3c Fix warning message
Mouse "wheel button" is meaningless :)
6 years ago
Romain Vimont 080df5eb5d Fix switch/case code style
For readability and consistency, indent case statatements, and remove
unnecessary additional blocks.
6 years ago
Romain Vimont d744837f13 Bump version to 1.1 6 years ago
Romain Vimont f7bc0bd5b5 Merge branch 'dev' into release 6 years ago
Romain Vimont 8a3c6a3ae7 Remove useless argument
Do not pass any data to the event watcher, it is unused.
6 years ago
Romain Vimont 0b1e59186f Workaround continuous resizing on Windows/MacOS
On Windows and MacOS, resizing blocks the event loop, so resizing events
are not triggered:
 - <https://bugzilla.libsdl.org/show_bug.cgi?id=2077>
 - <https://stackoverflow.com/a/40693139/1987178>

As a workaround, register an event watcher to render the screen from
another thread.

Since the whole event loop is blocked during resizing, the screen
content is not refreshed (on Windows and MacOS) until resizing ends.
6 years ago
Romain Vimont e69f6f710d Disable stdout/stderr buffering on Windows
In MSYS2 on Windows, the output is buffered by default. Disable
buffering to print output immediately.

Note that in cmd.exe, it still prints nothing.
6 years ago
Romain Vimont b858204786 Remove black borders on double-click
Resize the window to fit the device screen on click on black borders
(same as Ctrl+x).

Suggested-by: Guillaume Roche <groche@genymobile.com>
6 years ago
Romain Vimont 1038bad385 Make it work over tcpip
"adb reverse" currently does not work over tcpip (i.e. on a device
connected by "adb connect"):
<https://issuetracker.google.com/issues/37066218>

To work around the problem, if the call to "adb reverse" fails, then
fallback to "adb forward", and reverse the client/server roles.

Keep the "adb reverse" mode as the default because it does not involve
connection retries: when using "adb forward", the client must try to
connect successively until the server listens.

Due to the tunnel, every connect() will succeed, so the client must
attempt to read() to detect a connection failure. For this purpose, when
using the "adb forward" mode, the server initially writes a dummy byte,
read by the client.

Fixes <https://github.com/Genymobile/scrcpy/issues/5>.
6 years ago
Romain Vimont 2b3ed5bcdb Store serial in server instance
The serial is needed for many server actions, but this is an
implementation detail, so the caller should not have to provide it on
every call.

Instead, store the serial in the server instance on server_start().

This paves the way to implement the "adb forward" fallback properly.
6 years ago
Romain Vimont 9e328ef98b Always use the best render scale quality available
Because why not.

See <https://wiki.libsdl.org/SDL_HINT_RENDER_SCALE_QUALITY>.
6 years ago
Romain Vimont f9a63ec272 Reverse horizontal scrolling behavior
The SDL mouse wheel event seems inconsistent between horizontal and
vertical scrolling.

> Movements to the left generate negative x values and to the right
> generate positive x values. Movements down (scroll backward) generate
> negative y values and up (scroll forward) generate positive y values.

<https://wiki.libsdl.org/SDL_MouseWheelEvent#Remarks>

Reverse the horizontal.

Fixes <https://github.com/Genymobile/scrcpy/issues/49>.
6 years ago
Romain Vimont c87d94ee27 Map middle-click to HOME
Middle-click is useless in practice. Use it for HOME.
6 years ago
Romain Vimont 675704c71c Map right-click to BACK if screen is on
Right-click was used to turn the screen on. It did nothing when the
screen was already on.

Instead, in that case, press BACK (like Vysor).

Suggested by: <https://www.reddit.com/r/Android/comments/834zmr/introducing_scrcpy_an_app_to_display_and_control/dvfueft/>
6 years ago
Romain Vimont 9396ea6d42 Fix text input event segfault
The text input control_event was initially designed for mapping
SDL_TextInputEvent, limited to 32 characters.

For simplicity, the copy/paste feature was implemented using the same
control_event: it just sends the text to paste.

However, the pasted text might have a length breaking some assumptions:
 - on the client, the event max-size was smaller than the text
   max-length,
 - on the server, the raw buffer storing the events was smaller than the
   max event size.

Fix these inconsistencies, and encode the length on 2 bytes, to accept
more than 256 characters.

Fixes <https://github.com/Genymobile/scrcpy/issues/10>.
6 years ago
Romain Vimont f9562f537a Unref the packet on error
Do not leak the packet data on error.
6 years ago
Romain Vimont a34fbd23e9 Do not leak the packet data
Oops! The content of the packets were never freed.
6 years ago
Romain Vimont c2ac6fe7bd Upgrade version to 1.0 6 years ago
Romain Vimont e2a7abcd53 Implement clipboard paste
Paste computer clipboard to the device on Ctrl+v.

The other direction (pasting the device clipboard to the computer) is
not implemented. It would require a communication channel from the
device to the computer, other than the socket used by the video stream.
6 years ago
Romain Vimont e4d64e8752 Initialize struct field by field
Initializing with braces initializes the other fields to 0, which is not
necessary.
6 years ago
Romain Vimont fffeedffda Expose High DPI support configuration flag
The High DPI support is enabled by default, so that the renderer use the
full definition of High DPI screens.

However, there are still mouse coordinates problems on some MacOS having
High DPI support (but not all), so expose a way to disable it.
6 years ago
Romain Vimont 82b4acee73 Do not fail on EAGAIN
A call to avcodec_receive_frame() may return AVERROR(EAGAIN) if more
input is required. This is not an error, do not fail.
6 years ago
Romain Vimont ab780ce26d Avoid useless variables initialization
Initialize variables only when necessary.
6 years ago
Romain Vimont 84ad6633a6 Move the new avcodec implementation before the old
The API to decode the video frames is different depending on the
libavcodec version.

Move the new API usage to the #if-block.
6 years ago
Romain Vimont 1b0cea61a5 Do not use return code for thread run function
The decoder sometimes returned a non-zero value on error, but not on
every path.

Since we never use the value, always return 0 at the end (like in the
controller).
6 years ago
Romain Vimont 42f6341a14 Revert "Enable high dpi support"
Just enabling this flag breaks mouse location values.

This reverts commit 38b56f552e.
6 years ago
Romain Vimont acd2dc3183 Shutdown sockets before closing
The server socket does not release the port it was listening for if we
just close it: we must also shutdown it.
6 years ago
Romain Vimont db396f2138 Fix scroll wheel mouse position
SDL_MouseWheelEvent does not provide the mouse location, so we used
SDL_GetMouseState() to retrieve it.

Unfortunately, SDL_GetMouseState() returns a position expressed in the
window coordinate system while the position filled in SDL events are
expressed in the renderer coordinate system. As a consequence, the
scroll was not applied at the right position on the device.

Therefore, convert the coordinate system.

See <https://stackoverflow.com/questions/49111054/how-to-get-mouse-position-on-mouse-wheel-event>.
6 years ago
Romain Vimont e6feb991db Fix comment typo
Replace "at network level" by "at the network level".
6 years ago
Romain Vimont e3f5d3b49b Double the default bitrate
Set the default video bitrate to 8Mbps. This greatly increase quality on
fast motion, without negative side effects.
6 years ago
Romain Vimont 38b56f552e Enable high dpi support
Use high DPI if available.

Note that on Mac OS X, setting this flag is not sufficient:

> On Apple's OS X you must set the NSHighResolutionCapable Info.plist
> property to YES, otherwise you will not receive a High DPI OpenGL
> display.

<https://wiki.libsdl.org/SDL_CreateWindow#flags>
6 years ago
Romain Vimont c78ad6377c Terminate the server on stop
On user request to quit, two kinds of blocking calls must be interrupted
on the server:
 1. the reads from and writes to the socket;
 2. the call to MediaCodec.dequeueOutputBuffer().

The former case was handled by calling shutdown() on the socket from the
client, but the latter was not managed.

There is no easy way to wake this call properly, so just terminate the
process from the client (i.e. send SIGTERM on Linux) instead.
6 years ago
Romain Vimont 221a7d0826 Clean up the server from temporary folder
The server is copied to /data/local/tmp/scrcpy-server.jar and executed
on the device.

As soon as we are connected, we can unlink (rm) it from /data/local/tmp,
to keep the device clean.
6 years ago
Romain Vimont 08d32e3bae Clean up useless const-casts
The function adb_execute() now expects a "const char *const *" parameter
for the adb command, so there is no need to cast.
6 years ago
Romain Vimont 487cb10cf0 Rename ScrCpyServer to Server
The Server class is in package scrcpy, there is no need to repeat the
name in the classname.
6 years ago
Romain Vimont 089378926b Rename SCRCPY_SERVER_JAR to SCRCPY_SERVER_PATH
The server is currently a JAR, but it may ba an APK or a DEX, so the
variable name should not contain the type.

Rename the environment variable, the Meson options and the C
definitions.
6 years ago
Romain Vimont 60f3185185 Reuse server address
Set SO_REUSEADDR flag to server socket, so that bind() does not fail if
we restart scrcpy immediately after we closed the previous one.
6 years ago
Romain Vimont 6db22ef339 Log socket errors
Do not silently ignore close() and shutdown() errors, and use perror()
to get the errno.
6 years ago
Romain Vimont ad6209f6ff Terminate the device process gracefully
Call shutdown() on the device socket to make the device process finish
its execution quickly and gracefully, without killing it.
6 years ago
Romain Vimont a791c272bc Send and recv all data when necessary
Expose net_recv_all() and net_send_all(), equivalent of net_recv() and
net_send(), but that waits/retries until the requested length has been
transferred.

Use these new functions where it was (wrongly) assumed that the
requested length had been transferred.
6 years ago
Romain Vimont d646f95a31 Avoid division by 0
If the frame_size width or height is 0, just return the current size to
avoid calculations involving divison by 0.
6 years ago
Romain Vimont 27b9159b07 Cleanup old code comment 6 years ago
Romain Vimont cf59d49d25 Detect failure of device information read
If the received data is smaller than the device information size, then
something is wrong.
6 years ago
Romain Vimont 9b056f5091 Replace SDL_net by custom implementation
SDL_net is not very suitable for scrcpy.

For example, SDLNet_TCP_Accept() is non-blocking, so we have to wrap it
by calling many SDL_Net-specific functions to make it blocking.

But above all, SDLNet_TCP_Open() is a server socket only when no IP is
provided; otherwise, it's a client socket. Therefore, it is not possible
to create a server socket bound to localhost, so it accepts connections
from anywhere.

This is a problem for scrcpy, because on start, the application listens
for nearly 1 second until it accepts the first connection, supposedly
from the device. If someone on the local network manages to connect to
the server socket first, then they can stream arbitrary H.264 video.
This may be troublesome, for example during a public presentation ;-)

Provide our own simplified API (net.h) instead, implemented for the
different platforms.
6 years ago
Romain Vimont bf41e5479b Improve decoder stopped event
The syntax was correct, but less readable, and it unnecessarily zeroed
the fields other than "type".

Create the event properly, from a separate method.
6 years ago
Romain Vimont 518d6d5dcd Prevent new window opening with CreateProcess()
Executing commands (like "adb push") created a new terminal window on
Windows. Avoid it.
6 years ago
Romain Vimont e8cad790a4 Reword Ctrl+x description
Pressing Ctrl+x resizes the window to remove black borders, "optimal" is
not well-defined.
6 years ago
Romain Vimont 5ebf31d483 Remove useless screen render on initialization
screen_render() should not be called on initialization:
 1. it is useless, since the window is hidden until the first frame;
 2. it writes an empty texture (probably green) to the renderer.
6 years ago
Romain Vimont d977202224 Add Ctrl+i shortcut to enable/disable FPS counter
Disable FPS counter on start, and use Ctrl+i to enable/disable it.
6 years ago
Romain Vimont 000ced9ba8 Refactor screencontrol to inputmanager
The "screen control" handled user input, which happened to be only
used to control the screen.

The controller and screen were passed to every function. Instead, group
them in a struct input_manager.

The purpose is to add a new shortcut to enable/disable FPS counter. This
feature is not related to "screen control", and will require access to
the "frames" instance.
6 years ago
Romain Vimont 42882702d7 Expose skip_frames as a build option
It can be initially configured by:

    meson builddir -Dskip_frames=false

Or on an existing builddir by:

    mesonconf builddir -Dskip_frames=false
6 years ago
Romain Vimont 38e6682875 Add FPS counter
Remove frame counter from scrcpy.c and add a new FPS counter, logging as
INFO the measured frame rate every second (on new frame).
6 years ago
Romain Vimont c6c17af840 Do not print usage on command error
On error, a message is printed. If we print usage afterwards, it's easy
to miss it.
6 years ago
Romain Vimont 8697659890 Expose device serial as an optional argument
The device serial was provided as a positional argument:

    scrcpy 0123456789abcdef

Instead, expose it as an optional argument, -s or --serial:

    scrcpy -s 0123456789abcdef

This avoids inconsistency between platforms when the positional
argument is passed before the options (which is undefined).
6 years ago
Romain Vimont 23d92a95b6 Extract argument parsing to specific functions
To avoid a big switch/case, implement the argument parsing logic in
separate static functions.
6 years ago
Romain Vimont 111068d733 Use SDL_bool return to indicate success
For clarity and consistency across the application, return SDL_TRUE
(instead of 0) on success and SDL_FALSE on failure (instead of
non-zero).
6 years ago
Romain Vimont d3c76c004e Sort parameters by letter
For readability, sort the command-line arguments parsing by letter.
6 years ago
Romain Vimont 0efa9305eb Require Meson 0.37
Older versions of Meson are too limited, and it's simple to install a
newer version ("pip3 install meson").
6 years ago
Romain Vimont c2127d0819 Replace meson subprojects by subdir
Since Meson 0.44, subproject_dir may not be '.' anymore. This implies we
must move app/ and server/ to a subprojects/ directory, which requires
to also change some gradle files.

Instead, just use subdir(), with options to disable building of the app
or the server.
6 years ago
Romain Vimont ff94462d8a Refactor build system
The client was built with Meson, the server with Gradle, and were run by
a Makefile.

Add a Meson script for the server (which delegates to Gradle), and a
parent script to build and install both the client and the server to the
system, typically with:

    meson --buildtype release build
    cd build
    ninja
    sudo ninja install

In addition, use a separate Makefile to build a "portable" version of
the application (where the client expects the server to be in the
current directory). Typically:

    make release-portable
    cd dist/scrcpy
    ./scrcpy

This is especially useful for Windows builds, which are not "installed".
6 years ago
Romain Vimont 396df8a9d8 Provide config.h.in for old meson versions
The current meson version is able to generate a config.h from a
configuration data object without any template.

However, older versions of meson require a template, so provide it for
compatibility.
6 years ago
Romain Vimont 3ed80a1fac Define macros wrappers for logs
Use macros to wrap SDL_Log* functions with the "application" category.
6 years ago
Romain Vimont d45ef1a295 Do not use too recent set_quoted()
Old versions of meson do not support set_quoted(). Replace the call by
the old-fashioned manual quotation.
6 years ago
Romain Vimont ad41bacb48 Fix "terminate process" on Windows
CloseHandle() does not terminate the process. TerminateProcess() does.
6 years ago
Romain Vimont 6fe65d9f5c Log with category APPLICATION
All our logs should use APPLICATION category. The logs for other
categories are not printed by default under the "critical" level.
6 years ago
Romain Vimont 4dbc450d01 Enable debug logs only for debug builds
In release mode, use the default log priorities.
6 years ago
Romain Vimont 0fce4f95b9 Properly clean up on exit
The SDL clean up does not crash anymore on exit, probably since the
memory corruption caused by calling SDLNet_TCP_Close() too early has
been resolved.
6 years ago
Romain Vimont eb09fefd43 Timeout the server socket connection
Wait no more than 2 seconds for accepting the connection from the
device, since it blocks the event loop, preventing to react to SIGTERM
(Ctrl+C).
6 years ago
Romain Vimont 90a46b4c45 Improve startup time
On startup, the client has to:
 1. listen on a port
 2. push and start the server to the device
 3. wait for the server to connect (accept)
 4. read device name and size
 5. initialize SDL
 6. initialize the window and renderer
 7. show the window

From the execution of the app_process command to start the server on the
device, to the execution of the java main method, it takes ~800ms. As a
consequence, step 3 also takes ~800ms on the client.

Once complete, the client initializes SDL, which takes ~500ms.

These two expensive actions are executed sequentially:

                     HOST              DEVICE
listen on port        |                  |
push/start the server |----------------->|| app_process loads the jar
accept the connection .   ^              ||
                      .   |              ||
                      .   | WASTE        ||
                      .   |  OF          ||
                      .   | TIME         ||
                      .   |              ||
                      .   |              ||
                      .   v              X execution of our java main
connection accepted   |<-----------------| connect to the host
init SDL             ||                  |
                     || ,----------------| send frames
                     || |,---------------|
                     || ||,--------------|
                     || |||,-------------|
                     || ||||,------------|
init window/renderer  | |||||,-----------|
display frames        |<++++++-----------|
(many frames skipped)

The rationale for step 3 occuring before step 5 is that initializing
SDL replaces the SIGTERM handler to receive the event in the event loop,
so pressing Ctrl+C during step 5 would not work (since it blocks the
event loop).

But this is not so important; let's parallelize the SDL initialization
with the app_process execution (we'll just add a timeout to the
connection):

                     HOST              DEVICE
listen on port        |                  |
push/start the server |----------------->||app_process loads the jar
init SDL             ||                  ||
                     ||                  ||
                     ||                  ||
                     ||                  ||
                     ||                  ||
                     ||                  ||
accept the connection .                  ||
                      .                  X execution of our java main
connection accepted   |<-----------------| connect to the host
init window/renderer  |                  |
display frames        |<-----------------| send frames
                      |<-----------------|

In addition, show the window only once the first frame is available to
avoid flickering (opening a black window for 100~200ms).

Note: the window and renderer are initialized after the connection is
accepted because they use the device information received from the
device.
6 years ago
Romain Vimont 523097eadf Provide decoder_init()
Expose an initializer so that the caller does not have to guess what
fields must be initialized.
6 years ago
Romain Vimont 4662198261 Do not release TCP sockets while still in use
SDLNet_TCP_Close() not only closes, but also release the resources.

Therefore, we must not close the socket if another thread attempts to
read it.

For that purpose, move socket closing from server_stop() to
server_destroy().
6 years ago
Romain Vimont fe21d9dfb5 Move frame updating to screen.c
Replace screen_update() by a higher-level screen_update_frame() handling
the whole frame updating, so that scrcpy.c just call it without managing
implementation details.
6 years ago
Romain Vimont 7458d8271e Kill the server immediately on close
Do not wait 100ms anymore to let the server print any exception: we
justly want to ignore them.

Moreover, there is no nanosleep() on Windows, so this solve another
problem.
6 years ago
Romain Vimont 2fdc368c41 Do not try to decode video when EOF is reached
When the video stream socket is closed and read_packey() returns -1,
av_read_frame() still returns 0.

To detect EOF, check the flag eof_reached in the AVIOContext.

This avoids garbage errors on closing.
6 years ago
Romain Vimont a8aa3d39b7 Send "screen on" command only on mouse down
Avoid to send the command twice, once on mouse down, once on mouse up.
6 years ago
Romain Vimont 127e56780a Fix deadlock on exit if SKIP_FRAMES disabled
On exit, the renderer will not consume frames anymore, so signal the
condition variable to wake up the decoder.
6 years ago
Romain Vimont 629c296207 Move frame swapping logic to frame.c
Expose frames_offer_decoded_frame() and frames_consume_rendered_frame()
so that callers are not exposed to frame swapping (between the decoding
and rendering frames) details.
6 years ago
Romain Vimont 0d7f050389 Unlock mutex on screen update failure
The mutex was not unlocked on all code paths.
6 years ago
Romain Vimont e8dfb723af Move control-related code to screencontrol.c
Move the code handling user input from scrcpy.c to a separate file,
screencontrol.c.
6 years ago
Romain Vimont e1749a0c09 Remove the "adb reverse" tunnel immediately
As soon as we accepted a connection, we can remove the "adb reverse"
tunnel.
6 years ago
Romain Vimont 3b06e7d500 Move device-related code to device.c
Move the code to read the initial device info from scrcpy.c to a
separate file, device.c.
6 years ago
Romain Vimont 28c5cc030b Move server-related code to server.c
The file server.c already existed, but exposed a low-level API. Make it
higher-level, so that scrcpy.c does not handle server details directly.
6 years ago
Romain Vimont 6c578b5caa Move screen-related code to screen.c
The file scrcpy.c contains too many different things in addition to the
main logic, so move the screen code to a separate file, screen.c.
6 years ago
Romain Vimont 14c58546a7 Add missing include guards
In practice, these headers are included only once, but it's a good
practice to always use include guards.
6 years ago
Romain Vimont ffae15e36a Rename control to controller
The struct decoder is defined in decoder.h.

For naming consistency, define the struct controller in controller.h.
6 years ago
Romain Vimont 7b7fd77134 Add missing static
Some functions in scrcpy.c are not used outside the file, so declare
them static.
6 years ago
Romain Vimont f39de46a39 Add delay before stopping server
Let some time to print any exception trace before killing it.
6 years ago
Romain Vimont cb1428223f Log user request to quit
Log at debug level user requests to quit.
6 years ago
Romain Vimont 7fe11033cb Include dependencies version
On --version, also print the dependencies version scrcpy has been
compiled against.
6 years ago
Romain Vimont 9f6464acff Expose application version
Expose scrcpy version via -v or --version.
6 years ago
Romain Vimont 8d30d40b79 Make SKIP_FRAMES a compilation flag
The skip_frames flag was a non-configurable runtime flag. Since it is
not exposed to the user, there is no need for a (possible) runtime cost.

For testing purpose, we still want it to be configurable, so make it a
compilation flag.
6 years ago
Romain Vimont 53ff1aa410 Use meson to configure default values
Make meson generate config.h with configured values.
6 years ago
Romain Vimont cb7e29180f Change the window icon color in debug mode
To highlight the debug/release mode of the running application, use a
different window icon color in debug mode.
6 years ago
Romain Vimont 71c2bfdd22 Parse XPM without SDL_image
We encounter some problems with SDL2_image on MSYS2 (Windows), so
implement our own XPM parsing which does not depend on SDL_image.

The input XPM is considered safe (it's in our source repo), so do not
check XPM format errors. This implies that read_xpm() is not safe to
call on any unsafe input.

Although less straightforward, use SDL_CreateRGBSurfaceFrom() instead of
SDL_CreateRGBSurfaceWithFormatFrom() because it is available with SDL
versions older than 2.0.5.
6 years ago
Romain Vimont f22d4decca Enable mouse focus clickthrough only if available
The hint SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH appeared in SDL 2.0.5. Ignore
it if the SDL version is older.
6 years ago
Romain Vimont 52c89c7afb Add window icon
Add a bugdroid icon loaded from an XPM.
6 years ago
Romain Vimont 5eb91a4ca7 Fix scrcpy() return value
The scrcpy() function returns a SDL_bool to indicate its success, but
was initialized to 0 (SDL_FALSE) instead of SDL_TRUE.
6 years ago
Romain Vimont 69a359c7f4 Refactor actions calls
The purpose of handle_shortcut() was to group all actions together,
whether they are initiated from a text input event or a keycode event.

However, it did not handle the case where it was initiated from a mouse
event (a right-click must turn the screen on), since the action was
identified by the shortcut char.

Instead, expose one function per action, to be called directly from
where the event is handled.
6 years ago
Romain Vimont d73dee9833 fixup! Handle all shortcuts in the same function 6 years ago
Romain Vimont 0a70e24e80 Add new shortcuts description in help
Document the new shortcuts in the help (scrcpy --help).
6 years ago
Romain Vimont a139509f11 Turn screen on on right-click
The right-click is almost useless on Android, so use it to turn the
screen on.

Add a new control event type (command) to request the server to turn the
screen on.
6 years ago
Romain Vimont deba69d022 Handle all shortcuts in the same function
Shortcuts are sometimes initiated from a keycode event, and sometimes
from a text input event.

Move the handling to a unique function.
6 years ago
Romain Vimont 7f6a565401 Extract shortcut actions to separate functions
To simplify event handling code, move all actions to separate functions.
6 years ago
Romain Vimont f8ad007a28 Move switch fullscreen logs
Logs were printed by the caller of switch_fullscreen(). Move them inside
the function to simplify event handling code.
6 years ago
Romain Vimont 6fe7b84629 Add shortcuts for physical keys
Add shortcuts for HOME, BACK, APPS, POWER, VOLUME_UP and VOLUME_DOWN.
6 years ago
Romain Vimont 1faf6cfd9d Rename the server scrcpy-server.jar
The server is built as an APK to simplify the build, but in fact this is
a simple jar (it is not even signed).

In order to avoid confusion, rename it to .jar, so that users do not try
to "adb install" it.

Also rename it from "scrcpy" to "scrcpy-server" to distinguish from the
client-side.
6 years ago
Romain Vimont 2172c53b7b Force the server target filename
The server path may be customized using SCRCPY_APK. If its basename is
different from "scrcpy.apk", it will be pushed with a different name,
so the execution would fail.

Therefore, force the push target filename.
6 years ago
Romain Vimont ca44585f96 Do not send simple mouse move events
Moving the mouse without any button pressed has no effect on Android.
Therefore, do not even send these very frequent events.
6 years ago
Romain Vimont 79b28eb68f Enable mouse focus clickthrough
Consider a click to gain focus as a click on the device.
6 years ago
Romain Vimont 6b546a87ab Add bit-rate command-line option
Add a command-line option (-b/--bit-rate) to customize the video
bit-rate.
6 years ago
Romain Vimont 7fe7bbf58c Check empty string before strtol()
There is no need to call strtol() if the input string is empty.
6 years ago
Romain Vimont 3bc63708b4 Remove useless newlines in SDL_Log*
Trailing new line is not necessary in SDL_Log* methods.
6 years ago
Romain Vimont 2683fa20ed Add debug log for shortcuts
Add a debug log for every succeeded shortcut action.
6 years ago
Romain Vimont 274e1ac9ec Fix rotation bug in fullscreen mode on X11
On rotation, scrcpy resize the window to match the new rotation.
However, in fullscreen mode, setting the window size does not change the
windowed size on X11, so the behavior is incorrect.

To avoid the problem, apply the resize only after fullscreen is
disabled.
6 years ago
Romain Vimont 35a111d56e Add --help
Provide command-line help, with -h/--help option.
6 years ago
Romain Vimont ee93f3f23a Rename maximum_size to max_size
The long option is --max-size, so for consistency, adapt the code
accordingly.
6 years ago
Romain Vimont 213b721ff9 Use long command-line options
In addition to the short form (e.g. "-p"), add the long form ("--port").
6 years ago
Romain Vimont 60b2f2ca64 Indent switch blocks content
For readability, indent "case" in switch blocks.

Replace:

    switch (x) {
    case 1:
        // ...
    case 2:
        // ...
    case 3: { // a local scope block
        int i = 42;
        // ...
    }
    }

By:

    switch (x) {
        case 1:
            // ...
        case 2:
            // ...
        case 3: { // a local scope block
            int i = 42;
            // ...
        }
    }
6 years ago
Romain Vimont 628f88ab89 Use ADB environment variable
Use the ADB environment variable to provide a custom adb path.
6 years ago
Romain Vimont b67907e24e Convert server to an Android project
To simplify the device server-side build, use gradle to create an APK,
even if we use it as a simple jar, by running its main() method.
6 years ago
Romain Vimont 89f6a3cfe7 Handle resized video stream
Accept a parameter to limit the video size.

For instance, with "-m 960", the great side of the video will be scaled
down to 960 (if necessary), while the other side will be scaled down so
that the aspect ratio is preserved. Both dimensions must be a multiple
of 8, so black bands might be added, and the mouse positions must be
computed accordingly.
6 years ago
Romain Vimont 879941355d Swap position/point names
A point is a 2D vector. A position represent a point relative to the
screen size.
6 years ago
Romain Vimont 2aa15db210 Add shortcut to resize to ratio 1:1
Make Ctrl+g resize the window to the size of the video (pixel-perfect).
6 years ago
Romain Vimont ab2c3de9f5 Capture all Ctrl events
For consistency, capture all Ctrl events (not only those we react to).
6 years ago
Romain Vimont 2c35220618 Rename screen -> scrcpy -> main
Rename scrcpy.c to main.c (this file handles the command line parsing),
and screen.c to scrcpy.c (it exposes the entry point scrcpy()).
6 years ago
Romain Vimont 8984c1a7c4 Scale mouse events
The video screen size on the client may differ from the real device
screen size (e.g. the video stream may be scaled down). As a
consequence, mouse events must be scaled to match the real device
coordinates.

For this purpose, make the client send the video screen size along with
the absolute pointer location, and the server scale the location to
match the real device size before injecting mouse events.
6 years ago
Romain Vimont d7b00a9bab Move server-related functions to server.c
In addition to the functions to start/stop the server, move the
functions to push the jar and enable/disable the "adb reverse" tunnel.
6 years ago
Romain Vimont 7d67696b7e Extract server-related functions
To lighten screen.c, move start_server() and stop_server() to a separate
file.
6 years ago
Romain Vimont 52af91f6b0 Add unit tests for control event serialization
Test serialization of the 4 types of events (keycode, text, mouse,
scroll).
6 years ago
Romain Vimont 90c69d2c79 Use pointers-to-const where relevant
Explicitly declare const a function parameter intended to be read-only.
6 years ago
Romain Vimont 53cd59605a Ignore keycodes generating unwanted events
Ctrl, Alt, Shift and Meta should not be transmitted to the Android
device: they may generate unwanted events. For instance, resizing the
window using Alt+click will generate an Alt event which may open a menu
on the device.

All keycodes that generate a text input must also be excluded, to avoid
the text input to be written twice.
6 years ago
Romain Vimont 66b7a99db6 Fix includes windows-specific source
The header strutil.h is two levels above sys/win/command.c, and
SDL_log.h was missing.
6 years ago
Romain Vimont f75c404a26 Add tests for strutil
Test our custom string handling functions.
6 years ago
Romain Vimont cabb102a04 Implement keyboard/mouse control
To control the device from the computer:
 - retrieve mouse and keyboard SDL events;
 - convert them to Android events;
 - serialize them;
 - send them on the same socket used by the video stream (but in the
 opposite direction);
 - deserialize the events on the Android side;
 - inject them using the InputManager.
6 years ago
Romain Vimont 95591d2938 Move platform specific to sys/
Move unix/ and win/ to sys/, so that we can use android/ for android
headers without confusion.
7 years ago
Romain Vimont a919944372 Use _exit() instead of exit() in child process
exit() should not be called from within a child process, since it would
call functions registered with atexit(), and flush stdio streams. Use
_exit() instead.
7 years ago
Romain Vimont 07b3918129 Do not call SDL_Quit()
It may crash in i965_dri.so when calling SDL_Quit (probably a driver
bug). To avoid a segmentation fault, do not call SDL_Quit().
7 years ago
Romain Vimont a005df7b37 Always destroy in reverse order
For consistency and safety, always destroy objects in reverse order they
were initialized.
7 years ago
Romain Vimont de106747b6 Improve main() error handling
Parse the command-line arguments first, and do not ignore avformat
network init failure. At the end, deinit the avformat network.
7 years ago
Romain Vimont bb8afa9324 Fix comment about data sent over the socket
We now send the device name in addition to the screen dimensions on the
socket. Update the comment accordingly.
7 years ago
Romain Vimont d972a88c1a Optimize includes
Only include SDL_stdinc.h for SDL_bool, not the whole SDL.h.
7 years ago
Romain Vimont d5b349f670 Do not inline lockutil functions
This duplicates chars in the final binary.
7 years ago
Romain Vimont a9b276aa67 Remove useless forward declarations
The required headers are included anyway.
7 years ago
Romain Vimont b9c9466d65 Handle condition variable failure
Add condition variables function wrappers to handle unexpected failure.
7 years ago
Romain Vimont c4266e487b Rename (un)lock_mutex to mutex_(un)lock
For consistency, rename lock_mutex and unlock_mutex to mutex_lock and
mutex_unlock.
7 years ago
Romain Vimont ad667bfa20 Fix function signature
Use void for parameters (this project is in C).
7 years ago
Romain Vimont 37d88b8a6a Use SDL_bool return type instead of int
Many functions returned an int to indicate their success. For clarity,
use SDL_bool instead.
7 years ago
Romain Vimont 2b44052f80 Destroy condition variable on frames destruction
A condition variable was init for the "struct frames", but was never destroyed.
7 years ago
Romain Vimont 39fd6ce518 Send device name on the socket
Make the server send the device name along with the width and height, so
that the client may use it as the window title.
7 years ago
Romain Vimont 54d9148a36 Initial commit
Start a new clean history from here.
7 years ago