The project has 3 build dependencies:
- SDL
- FFmpeg
- libusb
For Windows, the release script downloaded pre-built build dependencies
(either from upstream, or from the scrcpy-deps repository).
Instead, download the source releases and build locally. This offers
more flexibility.
The official adb release is still downloaded and included as is in the
release archive (it is not a build dependency).
Also upgrade FFmpeg to 6.1.1 and libusb to 1.0.27.
PR #4713 <https://github.com/Genymobile/scrcpy/pull/4713>
Initially, if AOA initialization failed, default injection method was
used, in order to use the same command/shortcut when the device is
connected via USB or via TCP/IP, without changing the arguments.
Now that there are 3 keyboard modes, it seems unexpected to switch to
another specific mode if AOA fails (and it is inconsistent). If the user
explicitly requests AOA, then use AOA or fail.
Refs #2632 comment <https://github.com/Genymobile/scrcpy/pull/2632#issuecomment-945190859>
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
The options were deprecated, but for convenience, reassign them to
aliases for --keyboard=uhid and --mouse=uhid respectively.
Their long version (--hid-keyboard and --hid-mouse) remain deprecated.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
The keyboard settings can be opened by:
adb shell am start -a android.settings.HARD_KEYBOARD_SETTINGS
Add a shortcut (MOD+k) for convenience if the current keyboard is HID.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
On close, the controller is expected to throw an IOException because the
socket is closed, so the exception was ignored.
However, message handling actions may also throw IOException, and they
must not be silently ignored.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
There is a dependency cycle in the initialization order:
- keyboard depends on controller
- controller depends on acksync
- acksync depends on keyboard initialization
To break this cycle, bind the async instance to the controller in a
second step.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
Rename {keyboard,mouse}_inject to {keyboard,mouse}_sdk.
All implementations "inject" key events and mouse events, what differs
is the mechanism. For these implementations, the Android SDK API is used
to inject events.
Note that the input mode enum variants were already renamed
(SC_KEYBOARD_INPUT_MODE_SDK and SC_MOUSE_INPUT_MODE_SDK).
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
An event contained several fields:
- the accessory id
- the HID event data
- a field ack_to_wait specific to the AOA implementation.
Extract the HID event part to prepare the factorization of HID event
creation.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
Until now, there was two modes for keyboard and mouse:
- event injection using the Android system API (default)
- HID/AOA over USB
For this reason, the options were exposed as simple flags:
- -K or --hid-keyboard to enable physical keyboard simulation (AOA)
- -M or --hid-mouse to enable physical mouse simulation (AOA)
Replace them by explicit --keyboard and --mouse options, with 3 possible
values:
- disabled
- sdk (default)
- aoa
This will allow to add a new mode (uhid).
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
The input manager assumed that if a controller was present, then both a
key processor and a mouse processor were present.
Remove this assumption, to support disabling keyboard and mouse
separately. This prepares the introduction of new command line options
--keyboard and --mouse.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
Some functions in input_manager.c only have access to a sub-object (for
example the controller). For consistency, always pass the whole
input manager instance.
This will allow to add assertions when keyboard and mouse could be
disabled separately.
PR #4473 <https://github.com/Genymobile/scrcpy/pull/4473>
The assumption that underflow and overbuffering are caused by jitter
(and that the delay between the producer and consumer will be caught up)
does not always hold.
For example, if the consumer does not consume at the expected rate (the
SDL callback is not called often enough, which is an audio output
issue), many samples will be dropped due to overbuffering, decreasing
the average buffering indefinitely.
Prevent the average buffering to become negative to limit the
consequences of an unexpected behavior.
PR #4572 <https://github.com/Genymobile/scrcpy/pull/4572>
The buffering level does not change continuously: it increases abruptly
when a packet is received, and decreases abruptly when an audio block is
consumed.
To estimate the buffering level, a rolling average is used.
To make the buffering more stable, increase the smoothness of this
rolling average. This decreases the risk of enabling audio compensation
due to an estimation error.
PR #4572 <https://github.com/Genymobile/scrcpy/pull/4572>
Use different thresholds for enabling and disabling compensation.
Concretely, enable compensation if the difference between the average
and the target buffering levels exceeds 4 ms (instead of 1 ms). This
avoids unnecessary compensation due to small noise in buffering level
estimation.
But keep a smaller threshold (1 ms) for disabling compensation, so that
the buffering level is restored closer to the target value. This avoids
to keep the actual level close to the compensation threshold.
PR #4572 <https://github.com/Genymobile/scrcpy/pull/4572>
The audio output thread only reads samples from the buffer, and most of
the time, the audio receiver thread only writes samples to the buffer.
In these cases, using atomics avoids lock contention.
There are still corner cases where the audio receiver thread needs to
"read" samples (and drop them), so lock only in these cases.
PR #4572 <https://github.com/Genymobile/scrcpy/pull/4572>
Some actions may be performed when scrcpy exits, currently:
- disable "show touches"
- restore "stay on while plugged in"
- power off screen
- restore "power mode" (to disable "turn screen off")
They are performed from a separate process so that they can be executed
even when scrcpy-server is killed (e.g. if the device is unplugged).
The clean up actions to perform were configured when scrcpy started.
Given that there is no method to read the current "power mode" in
Android, and that "turn screen off" can be applied at any time using an
scrcpy shortcut, there was no way to determine if "power mode" had to be
restored on exit. Therefore, it was always restored to "normal", even
when not necessary.
However, setting the "power mode" is quite fragile on some devices, and
may cause some issues, so it is preferable to call it only when
necessary (when "turn screen off" has actually been called).
For that purpose, make the scrcpy-server main process and the clean up
process communicate the actions to perform over a pipe (stdin/stdout),
so that they can be changed dynamically. In particular, when the power
mode is changed at runtime, notify the clean up process.
Refs 1beec99f82
Refs #4456 <https://github.com/Genymobile/scrcpy/issues/4456>
Refs #4624 <https://github.com/Genymobile/scrcpy/issues/4624>
PR #4649 <https://github.com/Genymobile/scrcpy/pull/4649>
This exception is a super-type of:
- ClassNotFoundException
- IllegalAccessException
- InstantiationException
- InvocationTargetException
- NoSuchFieldException
- NoSuchMethodException
Use it to simplify.
Create the service managers from each manager wrapper class rather than
from their getter in ServiceManager.
The way a wrapper retrieve the underlying service is an implementation
detail, and it must be consistent with the way it accesses it, so it is
better to write the creation in the wrapper.
Power on the device on start only if video capture is enabled.
Note that it only impacts display mirroring, since control is completely
disabled if video source is camera.
Refs 110b3a16f6
If the initial timestamp could not be retrieved, use the current time as
returned by System.nanoTime(). In practice, it is the same time base as
AudioRecord timestamps.
Fixes#4536 <https://github.com/Genymobile/scrcpy/issues/4536>
The result is assigned to a long (64-bit signed integer), but the
intermediate multiplication was stored in an int (32-bit signed
integer).
This value is only used as a fallback when no timestamp could be
retrieved, that's why it did not cause too much harm so far.
Fixes#4536 <https://github.com/Genymobile/scrcpy/issues/4536>
Reported by checkstyle:
> [ant:checkstyle] [INFO]
> scrcpy/server/src/main/java/com/genymobile/scrcpy/wrappers/ClipboardManager.java:48:
> Line is longer than 150 characters (found 167). [LineLength]
For AV1, the config packet must not be merged with the next non-config
packet.
This fixes the following error when passing --video-codec=av1:
> INFO: [FFmpeg] libdav1d 1.3.0
> ERROR: [FFmpeg] Unknown OBU type 0 of size 29393
> ERROR: [FFmpeg] Error parsing OBU data
> ERROR: Decoder 'video': could not send video packet: -1094995529
PR #4487 <https://github.com/Genymobile/scrcpy/pull/4487>
The SDL video subsystem may be initialized so that clipboard
synchronization works even without video playback.
But if the video subsystem initialization fails (e.g. because no video
device is available), consider it as an error only if video playback is
enabled.
Refs 5e59ed3135Fixes#4477 <https://github.com/Genymobile/scrcpy/issues/4477>
On some Samsung devices, DisplayManagerGlobal.getDisplayInfoLocked()
calls ActivityThread.currentActivityThread().getConfiguration(), which
requires a non-null ConfigurationController.
Fixes <https://github.com/Genymobile/scrcpy/issues/4467>
Fix the following warning/error:
../app/src/cli.c:2158:17: warning: a label can only be part of a
statement and a declaration is not a statement [-Wpedantic]
With some compilers, this is an error rather than a pedantic warning.
Refs <https://github.com/Genymobile/scrcpy/issues/2256#issuecomment-1467008307>
Install all the prebuilt dependencies for Windows to a specific folder,
and use meson command line options to specify their location.
This removes crossbuild-specific code from the meson scripts and will
simplify dependency upgrades.
PR #4460 <https://github.com/Genymobile/scrcpy/pull/4460>
On Android 14 (Pixel 8), a device rotation while the camera app was
running resulted in an incorrect capture.
Destroying and recreating the display fixes the issue.
Audio PTS are retrieved by AudioRecord.getTimestamp(), so they do not
necessarily exactly match the number of samples (this allows to take
drift and lag into account).
As a consequence, two consecutive timestamps in microseconds may
sometimes end up within the same millisecond, causing the warning. This
is particularly true for the Matroska muxer which uses a timebase of
1/1000 (1 ms precision).
Since this is "expected", lower the log level from warning to debug.
If the difference of PTS between two consecutive blocks of audio is less
than 1 sample, then it will be considered as non-increasing by FFmpeg
muxers having a time_base of 1/sample_rate.
Increase the PTS by 1 sample instead.
If several reads are performed for a single captured audio block (e.g.
if the read size is smaller than the captured block), then the provided
timestamp was the same for all packets.
Recompute the timestamp for each of them.
In practice, the system captures audio samples by blocks of 1024
samples.
Remplace the hardcoded value of 5 milliseconds (240 samples), and let
AudioRecord fill the input buffer provided by MediaCodec (or by
AudioRawRecorder), with a maximum size of 1024 samples (just in case).
FLAC is not low latency: the default encoder produces blocks of 4096
samples, which represent ~85.333ms.
Increase the audio buffer by default so that audio playback works.
It is incorret to ever call:
streamer.writeDisableStream(...);
after:
streamer.writeAudioHeader();
Move the try-catch block so that it can never happen.
Some devices may provide invalid ranges, causing an
IllegalArgumentException "lower must be less than or equal to upper".
Catch the exception to list the cameras anyway.
Refs #4403 <https://github.com/Genymobile/scrcpy/issues/4403>
Interrupting async processors may require to shutdown the connection to
wake up blocking calls.
Therefore, shutdown the connection first, then join the threads, then
close the connection.
Refs commit 9c08eb79cb
Add --camera-high-speed to enable high frame rate camera capture. If
the option is enabled, then --camera-fps is mandatory.
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
Add a new option for specifying the camera frame rate.
By default, Android's default frame rate (30 fps) is used.
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Signed-off-by: Andrew Gunnerson <accounts+github@chiller3.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
In addition to --camera-size to specify an explicit size, make it
possible to select the camera size automatically, respecting the maximum
size (already used for display mirroring) and an aspect ratio.
For example, "scrcpy --video-source=camera" followed by:
- (no additional arguments)
: mirrors at the maximum size, any a-r
- -m1920
: only consider valid sizes having both dimensions not above 1920
- --camera-ar=4:3
: only consider valid sizes having an aspect ratio of 4:3 (+/- 10%)
- -m2048 --camera-ar=1.6
: only consider valid sizes having both dimensions not above 2048
and an aspect ratio of 1.6 (+/- 10%)
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Co-authored-by: Simon Chan <1330321+yume-chan@users.noreply.github.com>
Add an option to select the camera by its lens facing (front, back or
external).
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
If --audio-source is not specified, select the default value
according to the video source:
- for display mirroring, use device audio by default;
- for camera mirroring, use microphone by default.
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Extract an interface SurfaceCapture from ScreenEncoder, representing a
video source which can be rendered to a Surface for encoding.
Split ScreenEncoder into:
- ScreenCapture, implementing SurfaceCapture to capture the device
screen,
- SurfaceEncoder, to encode any SurfaceCapture.
This separation prepares the introduction of another SurfaceCapture
implementation to capture the camera instead of the device screen.
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
By default, the Java process exits when all non-daemon threads are
terminated.
The Android SDK might start some non-daemon threads internally,
preventing the scrcpy server to exit in some cases.
So force the process to exit explicitly.
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
The option is named "display id" everywhere.
This will be consistent with --camera-id (there will be many camera
options, so an option --camera would be confusing).
PR #4213 <https://github.com/Genymobile/scrcpy/pull/4213>
The script install_release.sh downloads a file named scrcpy-server to
the repo root directory. Add it to .gitignore so that it is ignored.
PR #4364 <https://github.com/Genymobile/scrcpy/pull/4364>
Signed-off-by: Romain Vimont <rom@rom1v.com>
If --no-video was set, then device disconnection was not reported. To
avoid the problem, report device disconnection also on audio
end-of-stream (EOS).
If both video and audio are enabled, then a device disconnection event
will be sent twice, but only the first one will be handled (since it
makes scrcpy exit).
Fixes#4207 <https://github.com/Genymobile/scrcpy/issues/4207>
Some devices (Meizu) assume that the video encoding thread has a
Looper. By moving video encoding to a separate thread, commit
feab87053a broke this assumption.
Call Looper.prepare() from this thread to fix the problem.
Fixes#4143 <https://github.com/Genymobile/scrcpy/issues/4143>
On sway (a window manager), SDL_WINDOWEVENT_EXPOSED and
SDL_WINDOWEVENT_SIZE_CHANGED might not be called before a mouse event is
triggered. As a consequence, the "content rectangle" might not be
initialized when the mouse event is processed, causing a division by
zero.
To avoid the problem, initialize the content rect immediately when the
window is shown.
Fixes#4115 <https://github.com/Genymobile/scrcpy/issues/4115>
In forward mode, the dummy byte must be written immediately after the
first accept(), otherwise the client will wait indefinitely, causing a
deadlock (or a timeout).
Regression introduced by 8c650e53cd.
Audio did not work on Honor devices.
To make it work, a system context must be set as a base context of
FakeContext (so that a PackageManager is available), and a current
Application and ActivityThread must be set.
These workarounds must not be applied for all devices, because they
might cause other issues.
Fixes#4015 <https://github.com/Genymobile/scrcpy/issues/4015>
Refs #3085 <https://github.com/Genymobile/scrcpy/issues/3805>
Co-authored-by: Simon Chan <1330321+yume-chan@users.noreply.github.com>
In the recorder, if the video or audio stream is disabled, do not wait
for its initialization (it will never happen) to process the header.
In that case (scrcpy --no-audio --record=file.mp4), this caused the
whole content to be buffered in memory, and written only on exit.
The sc_cond_wait() in sc_recorder_process_header() needs to be notified
of changes to video_init/audio_init (protected by stream_cond) and
video_queue/audio_queue (protected by queue_cond).
Use only one condition variable to simplify.
The flag is used to reset the capture (restart the encoding) on rotation
change. It will also be used for other events (on folding change), so
rename it.
PR #3979 <https://github.com/Genymobile/scrcpy/pull/3979>
The comment was outdated:
- the "meta" header is now always present (not only when recording is
enabled);
- it is not only used for the video stream, but also for the audio
stream.
On some window managers (e.g. on Windows), performing a resize while the
window is minimized does nothing (the restored window keeps its old
size).
Therefore, like for maximized and fullscreen states, wait for the window
to be restored to apply a resize.
Refs #3947 <https://github.com/Genymobile/scrcpy/issues/3947>
When the scrcpy window is minimized on Windows with D3D9, texture
creation and update fail.
In that case, do not terminate scrcpy. Instead, store the pending size
or frame to update, to attempt again during the next update or
rendering.
Fixes#3947 <https://github.com/Genymobile/scrcpy/issues/3947>
Some server parameters may depend on one another. For example,
audio_bit_rate is meaningless if audio is false.
But it is inconsistent to disable some parameters based on these
dependencies checks, but not others. Handling all dependencies between
parameters would add too much complexity for no benefit.
So just pass individual parameters independently.
PR #3978 <https://github.com/Genymobile/scrcpy/pull/3978>
Contrary to the other tasks (controller and audio capture/encoding), the
screen encoder was executed synchronously. As a consequence,
scrcpy-server could not terminate until the screen encoder returned.
Convert it to an async processor. This allows to terminate on controller
error, and this paves the way to disable video mirroring.
PR #3978 <https://github.com/Genymobile/scrcpy/pull/3978>
The async processors use the socket file descriptors from the
connection. Therefore, the connection must not be closed before all
async processor threads are joined.
PR #3978 <https://github.com/Genymobile/scrcpy/pull/3978>
Reword the supported API versions for audio forwarding sentence to
clarify that it supports API >= 30
PR #3949 <https://github.com/Genymobile/scrcpy/pull/3949>
Signed-off-by: Romain Vimont <rom@rom1v.com>
By default, SDL creates an OpenGL 2.1 context on macOS for an OpenGL
renderer. As a consequence, mipmapping is not supported.
Force to use a core profile context, to get a higher version.
Before:
INFO: Renderer: opengl
INFO: OpenGL version: 2.1 NVIDIA-14.0.32 355.11.11.10.10.143
WARN: Trilinear filtering disabled (OpenGL 3.0+ or ES 2.0+ required)
After:
INFO: Renderer: opengl
DEBUG: Creating OpenGL Core Profile context
INFO: OpenGL version: 4.1 NVIDIA-14.0.32 355.11.11.10.10.143
INFO: Trilinear filtering enabled
when running with:
scrcpy --verbosity=debug --render-driver=opengl
Note: Since SDL_CreateRenderer() causes a fallback to OpenGL 2.1, the
profile and version attributes have to be set and the context created
_after_.
PR #3895 <https://github.com/Genymobile/scrcpy/pull/3895>
Signed-off-by: Romain Vimont <rom@rom1v.com>
If a line did not end with '\r', then the final `\n' was replaced by
'\0' for parsing the current line. This `\0` was then mistakenly
considered as the end of the whole "ip route" output, so the remaining
lines were not parsed, causing "scrcpy --tcpip" to fail in some cases.
To fix the issue, read the final character of the current line before it
is (possibly) overwritten by '\0'.
The slope encodes the drift between the device clock and the computer
clock. Its real value is expected very close to 1.
To estimate it, just assume it is exactly 1.
Since the clock is used to estimate very close points in the future, the
error caused by clock drift is totally negligible, and in practice it is
way lower than the slope estimation error.
Therefore, only estimate the offset.
The code to start audio capture is more complicated for Android 11
(launch a fake popup, wait, make several attempts, close the shell
package).
Use a distinct code path specific to Android 11.
On Android 11, a fake popup must be briefly opened to make the system
think that the shell app is in the foreground so that audio may be
recorded.
Making the shell app foreground may take some time depending on the
device, so make 3 attempts, waiting 100ms before each.
Fixes#3796 <https://github.com/Genymobile/scrcpy/issues/3796>
On some systems, the SDL audio callback is not called frequently enough
(for example it requests 5ms of samples every 10ms), because the output
buffer is too small.
By default, we want to use a small value (5ms) to minimize latency and
buffer underrun, but if it does not work well, users need a way to
increase it.
Refs #3793 <https://github.com/Genymobile/scrcpy/issues/3793>
There were several workarounds applied in a single method. Some of them
are specific to Meizu phones, but cause issues on other devices.
Split the method to be able to only fill the app context for audio
capture without applying the Meizu workarounds.
Fixes#3801 <https://github.com/Genymobile/scrcpy/issues/3801>
scrcpy is available directly in the distro, drop link to the overlay
(which only contains older versions).
PR #3816 <https://github.com/Genymobile/scrcpy/pull/3816>
Signed-off-by: Romain Vimont <rom@rom1v.com>
An int was compared with an unsigned:
../app/src/audio_player.c:290:27: warning: comparison of integers of
different signs: 'int' and 'unsigned int' [-Wsign-compare]
if (abs(diff) < ap->sample_rate / 1000) {
~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~
In C, a label can only be followed by a statement, not a declaration.
An error in `app/src/screen.c` violated this, and led to a build error
with an error message similar to the one below:
../app/src/screen.c:821:13: error: expected expression
bool ok = sc_screen_init_size(screen);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/13.0.0/include/stdbool.h:15:14: note: expanded from macro 'bool'
#define bool _Bool
^
../app/src/screen.c:822:18: error: use of undeclared identifier 'ok'
if (!ok) {
^
2 errors generated.
This could be fixed by introducing a new block (or compound statement;
as is already being done in the next `case`). That is a statement.
Fixes#3785 <https://github.com/Genymobile/scrcpy/issues/3785>
PR #3787 <https://github.com/Genymobile/scrcpy/pull/3787>
Signed-off-by: Ruoyu Zhong <zhongruoyu@outlook.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
The README.md page is HUGE. Split it up.
Also document audio forwarding and improve installation instructions for
each platform and user documentation.
PR #3774 <https://github.com/Genymobile/scrcpy/pull/3774>
On buffer underflow, the average buffering must be updated, but it is
intended to be accessed only from the receiver thread.
Make the player and the receiver thread communicate the underflow via a
new field (ap->underflow).
On initial connection, scrcpy sent some device metadata:
- the device name (to be used as window title)
- the initial video size (before any frame or even SPS/PPS)
But it is better to provide the initial video size as part as the video
stream, so that it can be demuxed and exposed via AVCodecContext to
sinks.
This avoids to pass an explicit "initial frame size" for the screen, the
recorder and the v4l2 sink.
Previously, the packet sink push() implementation just set the codec and
notified a wait condition. Then the recorder thread read the codec and
created the AVStream.
But this was racy: an AVFrame could be pushed before the creation of the
AVStream, causing its video_stream_index or audio_stream_index to be
initialized to -1.
Also, in the future, the AVStream initialization might need data
provided by the packet sink open(), so initialize it there (with a
mutex).
The sc_file_pusher is lazy-initialized, but it was stopped and joined in
all cases (accessing uninitialized values).
Detected by poisoning the struct scrcpy instance with ASAN enabled.
All server logs were printed to stdout, while all client logs were
printed to stderr.
Instead, use stderr for warnings and errors, stdout for the others:
- stdout: verbose, debug, info
- stderr: warn, error
System.out.println() first prints the message, then the new line.
Between these two calls, the client might print a message, breaking
formatting.
Instead, call System.out.print() with '\n' appended to the message.
On the server side, several components are started, stopped and joined.
Extract an interface to handle them generically.
This will help to support both encoded and raw audio stream, because
they will be two different concrete components, but implementing the
same interface.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Expose an option to add a buffering delay (in milliseconds) before
playing audio.
This is similar to the options --display-buffer and --v4l2-buffer for
video frames.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Play the decoded audio using SDL.
The audio player frame sink receives the audio frames, resample them
and write them to a byte buffer (introduced by this commit).
On SDL audio callback (from an internal SDL thread), copy samples from
this byte buffer to the SDL audio buffer.
The byte buffer is protected by the SDL_AudioDeviceLock(), but it has
been designed so that the producer and the consumer may write and read
in parallel, provided that they don't access the same slices of the
ring-buffer buffer.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Simon Chan <1330321+yume-chan@users.noreply.github.com>
A delay buffer delayed all the frames except the first one, to open the
scrcpy window immediately and get a picture.
Make this feature optional, so that the delay buffer might also be used
for audio (especially for simulating a high delay for debugging).
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
For clarity, the fields used only when a delay was set were wrapped in
an anonymous structure.
Now that the delay buffer has been extracted to a separate component,
the delay is necessarily set (it may not be 0), so the fields are always
used.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
The components needing delayed frames (sc_screen and sc_v4l2_sink)
managed a sc_video_buffer instance, which itself embedded a
sc_frame_buffer instance (to keep only the most recent frame).
In theory, these components should not be aware of delaying: they should
just receive AVFrames later, and only handle a sc_frame_buffer.
Therefore, refactor sc_delay_buffer as a frame source (it consumes)
frames) and a frame sink (it produces frames, after some delay), and
plug an instance in the pipeline only when a delay is requested.
This also removes the need for a specific sc_video_buffer.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
There was a frame sink trait, implemented by components able to receive
AVFrames, but each frame source had to manually send frame to sinks.
In order to mutualise sink management, add a frame sink trait.
There was a packet sink trait, implemented by components able to
receive AVPackets, but each packet source had to manually send packets
to sinks.
In order to mutualise sink management, add a packet source trait.
A video buffer had 2 responsibilities:
- handle the frame delaying mechanism (queuing packets and pushing them
after the expected delay);
- keep only the most recent frame (using a sc_frame_buffer).
In order to be able to reuse only the frame delaying mechanism, extract
it to a separate component, sc_delay_buffer.
The video_buffer thread clears the queue once it is stopped, but new
frames might still be pushed asynchronously.
To avoid the problem, do not push any frame once the video_buffer is
stopped.
The packets queued for buffering were wrapped in a dynamically allocated
structure with a "next" field.
To avoid this additional layer of allocation and indirection, use a
VecDeque.
The packets queued for recording were wrapped in a dynamically allocated
structure with a "next" field.
To avoid this additional layer of allocation and indirection, use a
VecDeque.
Since in scrcpy a video packet passed to avcodec_send_packet() is always
a complete video frame, it is sufficient to call avcodec_receive_frame()
exactly once.
In practice, it also works for audio packets: the decoder produces
exactly 1 frame for 1 input packet.
In theory, it is an implementation detail though, so
avcodec_receive_frame() should be called in a loop.
By default, scrcpy mirrors only the video when audio capture fails on
the device. Add an option to force scrcpy to fail if audio is enabled
but does not work.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
On Android 11, it is possible to start the capture only when the running
app is in foreground. But scrcpy is not an app, it's a Java application
started from shell.
As a workaround, start an existing Android shell existing activity just
to start the capture, then close it immediately.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
If there is exactly one producer, then it can assume that the remaining
space in the buffer will only increase until it writes something.
This assumption may allow the producer to write to the buffer (up to a
known safe size) without any synchronization mechanism, thus allowing
to read and write different parts of the buffer in parallel.
The producer can then commit the write with a lock held, and update its
knowledge of the safe empty remaining space.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
When audio capture fails on the device, scrcpy continues mirroring the
video stream. This allows to enable audio by default only when
supported.
However, if an audio configuration occurs (for example the user
explicitly selected an unknown audio encoder), this must be treated as
an error and scrcpy must exit.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
If no bit-rate is passed, let the server use the default value (8Mbps).
This avoids to define a default value on both sides, and to pass the
default bit-rate as an argument when starting the server.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
The permission "android.permission.RECORD_AUDIO" has been added for
shell in Android 11.
Moreover, on lower versions, it may make the server segfault on the
device (happened on a Nexus 5 with Android 6.0.1).
Refs <4feeee8891%5E%21/>
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
By default, audio is enabled (--no-audio must be explicitly passed to
disable it).
However, some devices may not support audio capture (typically devices
below Android 11, or Android 11 when the shell application is not
foreground on start).
In that case, make the server notify the client to dynamically disable
audio forwarding so that it does not wait indefinitely for an audio
stream.
Also disable audio on unknown codec or missing decoder on the
client-side, for the same reasons.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
For video streams (at least H.264 and H.265), the config packet
containing SPS/PPS must be prepended to the next packet (the following
keyframe).
For audio streams (at least OPUS), they must not be merged.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
The client does not use the audio stream if there is no display and no
recording (i.e. only V4L2), so disable audio so that the device does not
attempt to capture it.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
For OPUS codec, FFmpeg expects the raw extradata, but MediaCodec wraps
it in some structure.
Fix the config packet to send only the raw extradata.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Create an AudioRecorder to capture the audio source REMOTE_SUBMIX.
For now, the captured packets are just logged into the console.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
When audio is enabled, open a new socket to send the audio stream from
the device to the client.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
Audio will be enabled by default (when supported). Add an option to
disable it.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
Remove USER_ID from ServiceManager, and replace it by a constant in
FakeContext.
This is the same as android.os.Process.ROOT_UID, but this constant has
been introduced in API 29.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Since scrcpy-server is not an Android application (it's a java
executable), it has no Context.
Some features will require a Context instance to get the package name
and the UID. Add a FakeContext for this purpose.
PR #3757 <https://github.com/Genymobile/scrcpy/pull/3757>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
The Callbacks interface notifies new packets. But in addition, the
screen encoder will need to write headers on start.
We could add a function onStart(), but for simplicity, just remove the
interface, which brings no value, and call the streamer directly.
Refs 87972e2022
On any error, all previously opened sockets must be closed.
Handle these errors in a single catch-block. Currently, there are only 2
sockets, but this will simplify even more with more sockets.
Note: this commit is better displayed with --ignore-space-change (-b).
The recorder opened the target file from the packet sink open()
callback, called by the demuxer. Only then the recorder thread was
started.
One golden rule for the recorder is to never block the demuxer for I/O,
because it would impact mirroring. This rule is respected on recording
packets, but not for the initial recorder opening.
Therefore, start the recorder thread from sc_recorder_init(), open the
file immediately from the recorder thread, then make it wait for the
stream to start (on packet sink open()).
Now that the recorder can report errors directly (rather than making the
demuxer call fail), it is possible to report file opening error even
before the packet sink is open.
The recorder has two initialization phases: one to initialize the
concrete recorder object, and one to open its packet_sink trait.
Initialize mutex and condvar as part of the object initialization.
If there were several packet_sink traits (spoiler: one for video, one
for audio), then the mutex and condvar would still be initialized only
once.
Stop scrcpy on recorder errors.
It was previously indirectly stopped by the demuxer, which failed to
push packets to a recorder in error. Report it directly instead:
- it avoids to wait for the next demuxer call;
- it will allow to open the target file from a separate thread and stop
immediately on any I/O error.
User-friendly error messages are printed on specific configuration
exceptions. In that case, do not print the stacktrace.
Also handle the user-friendly error message directly where the error
occurs, and print multiline messages in a single log call, to avoid
confusing interleaving.
On the scrcpy-deps repo, I built FFmpeg 5.1.2 binaries for Windows with
only the features used by scrcpy.
For comparison, here are the sizes of the dll for FFmpeg 5.1.2:
- before: 89M
- after: 4.7M
It also allows to upgrade the old FFmpeg version (4.3.1) used for win32.
Refs <https://github.com/rom1v/scrcpy-deps>
Refs <https://github.com/Genymobile/scrcpy/issues/1753>
As reported by gradle:
> Setting the namespace via a source AndroidManifest.xml's package
> attribute is deprecated.
>
> Please instead set the namespace (or testNamespace) in the module's
> build.gradle file, as described here:
> https://developer.android.com/studio/build/configure-app-module#set-namespace
Running scrcpy --tcpip on a device already connected via TCP/IP did not
initialize server->serial.
As a consequence, in debug mode, an assertion failed:
scrcpy: ../app/src/server.c:770: run_server: Assertion
`server->serial' failed.
In release mode, scrcpy failed with this error:
adb: -s requires an argument
Scrcpy does not use FFmpeg network features. Initialize network locally
instead (useful only for Windows).
The include block has been moved to fix the following warning:
Please include winsock2.h before windows.h
DesktopConnection implements Closeable, so it is implicitly closed after
its try-with-resources block. Closing the DesktopConnection shutdowns
the sockets, so it is necessary in particular to wake up blocking read()
calls from the controller.
But the controller thread was joined before the DesktopConnection was
closed, causing a deadlock. To fix the problem, join the controller
thread only after the DesktopConnection is closed.
Refs 400a1c69b1
When a call to a packet or frame sink fails, do not log the error on the
caller side: either the "failure" is expected (explicitly stopped) or it
must be logged by the packet or frame sink implementation.
On close, the client closes the socket. This wakes up socket blocking
calls on the server-side, by throwing an exception. Since this exception
is expected, it was not logged.
However, other IOExceptions might occur, which must not be ignored. For
that purpose, log only IOException when they are not caused by an EPIPE
error.
The PTS received from MediaCodec are expressed relative to an arbitrary
clock origin. We consider the PTS of the first frame to be 0, and the
PTS of every other frame is relative to this first PTS (note that the
PTS is only used for recording, it is ignored for mirroring).
For simplicity, this relative PTS was computed on the server-side.
To prepare support for multiple stream (video and audio), send the
packet with its original PTS, and handle the PTS offset on the
client-side (by the recorder).
Since we can't know in advance which stream will produce the first
packet with the lowest PTS (a packet received later on one stream may
have a PTS lower than a packet received earlier on another stream),
computing the PTS on the server-side would require unnecessary waiting.
On mouse click events:
- the first button pressed must first generate ACTION_DOWN;
- all button pressed (including the first one) must generate
ACTION_BUTTON_PRESS;
- all button released (including the last one) must generate
ACTION_BUTTON_RELEASE;
- the last button released must in addition generate ACTION_UP.
Otherwise, Chrome does not work properly.
Fixes#3635 <https://github.com/Genymobile/scrcpy/issues/3635>
Signed-off-by: Romain Vimont <rom@rom1v.com>
If the pointer is a mouse, the pointer is UP only when no buttons are
pressed (not when a button is released, because there might be other
buttons still pressed).
Refs #3635 <https://github.com/Genymobile/scrcpy/issues/3635>
Signed-off-by: Romain Vimont <rom@rom1v.com>
On click event, only the whole buttons state was passed to the device.
In addition, on ACTION_DOWN and ACTION_UP, pass the button associated to
the action.
Refs #3635 <https://github.com/Genymobile/scrcpy/issues/3635>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
MediaCodec may fail spuriously, typically when stopping an encoding and
starting a new one immediately (for example on device rotation).
In that case, retry a few times, in many cases it should work.
Refs #3693 <https://github.com/Genymobile/scrcpy/issues/3693>
For the initial connection between the device and the computer, an adb
tunnel is established (with "adb reverse" or "adb forward").
The device-side of the tunnel is a local socket having the hard-coded
name "scrcpy". This may cause issues when several scrcpy instances are
started in a few seconds for the same device, since they will try to
bind the same name.
To avoid conflicts, make the client generate a random UID, and append
this UID to the local socket name ("scrcpy_01234567").
Use av_packet_ref() to reference the packet without copy.
This also simplifies the logic, by making the "offset" variable and the
memcpy() call local to the if-block.
Right click and middle click require the source device to be a mouse,
not a touchscreen. Therefore, the source device was changed only when a
button other than the primary button was pressed (see
adc547fa6e).
However, this led to inconsistencies between the ACTION_DOWN when a
secondary button is pressed (with a mouse as source device) and the
matching ACTION_UP when the secondary button is released (with a
touchscreen as source device, because then there is no button pressed).
To avoid the problem in all cases, force a mouse as source device when
--forward-all-clicks is set.
Concretely, for mouse events in --forward-all-clicks mode:
- device source is set to InputDevice.SOURCE_MOUSE;
- motion event toolType is set to MotionEvent.TOOL_TYPE_MOUSE;
Otherwise (when --forward-all-clicks is unset, or for real touch
events), finger events are injected:
- device source is set to InputDevice.SOURCE_TOUCHSCREEN;
- motion event toolType is set to MotionEvent.TOOL_TYPE_FINGER.
Fixes#3568 <https://github.com/Genymobile/scrcpy/issues/3568>
PR #3579 <https://github.com/Genymobile/scrcpy/pull/3579>
Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
This fixes the following warning:
> WARNING: Running the setup command as `meson [options]` instead of
> `meson setup [options]` is ambiguous and deprecated.
If the current adb port is not 5555 (typically 0 because it is not in
TCP/IP mode), --tcpip automatically executes (among other commands):
adb tcpip 5555
In case adb was already listening on another port, this command forced
to listen on 5555, and the connection should still succeed.
But this reconfiguration might be inconvenient for the user. If adb is
already in TCP/IP mode, use the current enabled port without
reconfiguration.
Fixes#3591 <https://github.com/Genymobile/scrcpy/issues/3591>
Mandatory arguments may be passed in either of these two forms:
1. --key value
2. --key=value
Optional argument may only be passed in the second form.
For consistency, always document using --key=value.
Refs f76fe2c0d4
There were exactly one instance of ServiceManager and Settings, stored
in Device.
Since a Device instance is not created by the CleanUp executable, it was
not straightforward to call wrapper methods on cleanup.
Remove this artificial restriction and expose them publicly via static
methods (this is equivalent to expose a singleton, but less verbose).
Add a launcher which opens a terminal, and keep it open in case of
errors (so that the user has time to read error messages).
The behavior is the same as scrcpy-console.bat on Windows.
PR #3351 <https://github.com/Genymobile/scrcpy/pull/3351>
This lowers the barrier to contribute to translations, and frees up my
maintenance time used to review and merge translations and their updates
in many languages.
On Windows and macOS, resizing blocks the event loop. Handling it
properly would require the same workaround as done in screen.c.
This reverts commit 436b368f9d.
The previous commit replaced the IInterface instance (the "input"
service) by the InputManager instance (retrieved by
InputManager.getInstance()).
Both define an "injectInputEvent" method, but the alternate version
(probably) does not concern the InputManager.
This reverts commit b7a06278fe.
PR #3190 <https://github.com/Genymobile/scrcpy/pull/3190>
We must distinguish 3 cases for await_for_server():
- an error occurred
- no error occurred, the device is connected
- no error occurred, the device is not connected (user requested to
quit)
For this purpose, use an additional output parameter to indicate if the
device is connected (only set when no error occurs).
Refs #3085 <https://github.com/Genymobile/scrcpy/pull/3085>
Se più dispositivi sono connessi, riscontrerai questo errore:
> adb: error: failed to get feature set: more than one device/emulator
l'identificatore del tuo dispositivo deve essere fornito:
```bash
scrcpy -s 01234567890abcdef
```
Notare che se il tuo dispositivo è connesso mediante TCP/IP, riscontrerai questo messaggio:
> adb: error: more than one device/emulator
> ERROR: "adb reverse" returned with value 1
> WARN: 'adb reverse' failed, fallback to 'adb forward'
Questo è un problema atteso (a causa di un bug di una vecchia versione di Android, vedi [#5] (link in inglese)), ma in quel caso scrcpy ripiega su un metodo differente, il quale dovrebbe funzionare.
> adb server version (41) doesn't match this client (39); killing...
L'errore compare quando usi più versioni di `adb` simultaneamente. Devi trovare il programma che sta utilizzando una versione differente di `adb` e utilizzare la stessa versione dappertutto.
Puoi sovrascrivere i binari di `adb` nell'altro programma, oppure chiedere a _scrcpy_ di usare un binario specifico di `adb`, impostando la variabile d'ambiente `ADB`:
```bash
set ADB=/path/to/your/adb
scrcpy
```
### Device disconnected (Dispositivo disconnesso)
Se _scrcpy_ si interrompe con l'avviso "Device disconnected", allora la connessione `adb` è stata chiusa.
Prova con un altro cavo USB o inseriscilo in un'altra porta USB. Vedi [#281] (in inglese) e [#283] (in inglese).
Su alcuni dispositivi potresti dover abilitare un opzione che permette l'[input simulato][simulating input] (link in inglese). Nelle opzioni sviluppatore, abilita:
> **Debug USB (Impostazioni di sicurezza)**
> _Permetti la concessione dei permessi e la simulazione degli input mediante il debug USB_
<!--- Ho tradotto personalmente il testo sopra, non conosco esattamente il testo reale --->
Iniettare del testo in input è [limitato ai caratteri ASCII][text-input] (link in inglese). Un trucco permette di iniettare dei [caratteri accentati][accented-characters] (link in inglese), ma questo è tutto. Vedi [#37] (link in inglese).
Se la definizione della finestra del tuo client è minore di quella del tuo dispositivo, allora potresti avere una bassa qualità di visualizzazione, specialmente individuabile nei testi (vedi [#40] (link in inglese)).
Per migliorare la qualità di ridimensionamento (downscaling), il filtro trilineare è applicato automaticamente se il renderizzatore è OpenGL e se supporta la creazione di mipmap.
In Windows, potresti voler forzare OpenGL:
```
scrcpy --render-driver=opengl
```
Potresti anche dover configurare il [comportamento di ridimensionamento][scaling behavior] (link in inglese):
Ci potrebbero essere molte ragioni. Una causa comune è che il codificatore hardware del tuo dispositivo non riesce a codificare alla definizione selezionata:
> at android.media.MediaCodec.native_dequeueOutputBuffer(Native Method)
> ```
Prova con una definizione inferiore:
```
scrcpy -m 1920
scrcpy -m 1024
scrcpy -m 800
```
Potresti anche provare un altro [codificatore](README.it.md#codificatore).
## Linea di comando in Windows
Alcuni utenti Windows non sono familiari con la riga di comando. Qui è descritto come aprire un terminale ed eseguire `scrcpy` con gli argomenti:
1. Premi <kbd>Windows</kbd>+<kbd>r</kbd>, questo apre una finestra di dialogo.
2. Scrivi `cmd` e premi <kbd>Enter</kbd>, questo apre un terminale.
3. Vai nella tua cartella di _scrcpy_ scrivendo (adatta il percorso):
```bat
cd C:\Users\user\Downloads\scrcpy-win64-xxx
```
e premi <kbd>Enter</kbd>
4. Scrivi il tuo comando. Per esempio:
```bat
scrcpy --record file.mkv
```
Se pianifichi di utilizzare sempre gli stessi argomenti, crea un file `myscrcpy.bat` (abilita mostra [estensioni nomi file][show file extensions] per evitare di far confusione) contenente il tuo comando nella cartella di `scrcpy`. Per esempio:
_Only the original [README](README.md) is guaranteed to be up-to-date._
# scrcpy (v1.16)
Aplikasi ini menyediakan tampilan dan kontrol perangkat Android yang terhubung pada USB (atau [melalui TCP/IP][article-tcpip]). Ini tidak membutuhkan akses _root_ apa pun. Ini bekerja pada _GNU/Linux_, _Windows_ and _macOS_.
![screenshot](assets/screenshot-debian-600.jpg)
Ini berfokus pada:
- **keringanan** (asli, hanya menampilkan layar perangkat)
- **kinerja** (30~60fps)
- **kualitas** (1920×1080 atau lebih)
- **latensi** rendah ([35~70ms][lowlatency])
- **waktu startup rendah** (~1 detik untuk menampilkan gambar pertama)
- **tidak mengganggu** (tidak ada yang terpasang di perangkat)
scrcpy --lock-video-orientation 1 # 90° berlawanan arah jarum jam
scrcpy --lock-video-orientation 2 # 180°
scrcpy --lock-video-orientation 3 # 90° searah jarum jam
```
Ini mempengaruhi orientasi perekaman.
### Rekaman
Anda dapat merekam layar saat melakukan mirroring:
```bash
scrcpy --record file.mp4
scrcpy -r file.mkv
```
Untuk menonaktifkan pencerminan saat merekam:
```bash
scrcpy --no-display --record file.mp4
scrcpy -Nr file.mkv
# berhenti merekam dengan Ctrl+C
```
"Skipped frames" are recorded, even if they are not displayed in real time (for
performance reasons). Frames are _timestamped_ on the device, so [packet delay
variation] does not impact the recorded file.
"Frame yang dilewati" direkam, meskipun tidak ditampilkan secara real time (untuk alasan performa). Bingkai *diberi stempel waktu* pada perangkat, jadi [variasi penundaan paket] tidak memengaruhi file yang direkam.
Jika beberapa perangkat dicantumkan di `adb devices`, Anda harus menentukan _serial_:
```bash
scrcpy --serial 0123456789abcdef
scrcpy -s 0123456789abcdef # versi pendek
```
If the device is connected over TCP/IP:
```bash
scrcpy --serial 192.168.0.1:5555
scrcpy -s 192.168.0.1:5555 # versi pendek
```
Anda dapat memulai beberapa contoh _scrcpy_ untuk beberapa perangkat.
#### Mulai otomatis pada koneksi perangkat
Anda bisa menggunakan [AutoAdb]:
```bash
autoadb scrcpy -s '{}'
```
[AutoAdb]: https://github.com/rom1v/autoadb
#### Koneksi via SSH tunnel
Untuk menyambung ke perangkat jarak jauh, dimungkinkan untuk menghubungkan klien `adb` lokal ke server `adb` jarak jauh (asalkan mereka menggunakan versi yang sama dari _adb_ protocol):
```bash
adb kill-server # matikan server adb lokal di 5037
Aplikasi dapat dimulai langsung dalam layar penuh::
```bash
scrcpy --fullscreen
scrcpy -f # versi pendek
```
Layar penuh kemudian dapat diubah secara dinamis dengan <kbd>MOD</kbd>+<kbd>f</kbd>.
#### Rotasi
Jendela mungkin diputar:
```bash
scrcpy --rotation 1
```
Nilai yang mungkin adalah:
- `0`: tidak ada rotasi
- `1`: 90 derajat berlawanan arah jarum jam
- `2`: 180 derajat
- `3`: 90 derajat searah jarum jam
Rotasi juga dapat diubah secara dinamis dengan <kbd>MOD</kbd>+<kbd>←</kbd>
_(kiri)_ and <kbd>MOD</kbd>+<kbd>→</kbd>_(kanan)_.
Perhatikan bahwa _scrcpy_ mengelola 3 rotasi berbeda::
- <kbd>MOD</kbd>+<kbd>r</kbd> meminta perangkat untuk beralih antara potret dan lanskap (aplikasi yang berjalan saat ini mungkin menolak, jika mendukung orientasi yang diminta).
- `--lock-video-orientation` mengubah orientasi pencerminan (orientasi video yang dikirim dari perangkat ke komputer). Ini mempengaruhi rekaman.
memutar hanya konten jendela. Ini hanya mempengaruhi tampilan, bukan rekaman.
### Opsi pencerminan lainnya
#### Hanya-baca
Untuk menonaktifkan kontrol (semua yang dapat berinteraksi dengan perangkat: tombol input, peristiwa mouse, seret & lepas file):
```bash
scrcpy --no-control
scrcpy -n
```
#### Layar
Jika beberapa tampilan tersedia, Anda dapat memilih tampilan untuk cermin:
```bash
scrcpy --display 1
```
Daftar id tampilan dapat diambil dengan::
```
adb shell dumpsys display # cari "mDisplayId=" di keluaran
```
Tampilan sekunder hanya dapat dikontrol jika perangkat menjalankan setidaknya Android 10 (jika tidak maka akan dicerminkan dalam hanya-baca).
#### Tetap terjaga
Untuk mencegah perangkat tidur setelah beberapa penundaan saat perangkat dicolokkan:
```bash
scrcpy --stay-awake
scrcpy -w
```
Keadaan awal dipulihkan ketika scrcpy ditutup.
#### Matikan layar
Dimungkinkan untuk mematikan layar perangkat saat pencerminan mulai dengan opsi baris perintah:
```bash
scrcpy --turn-screen-off
scrcpy -S
```
Atau dengan menekan <kbd>MOD</kbd>+<kbd>o</kbd> kapan saja.
Untuk menyalakannya kembali, tekan <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>o</kbd>.
Di Android, tombol `POWER` selalu menyalakan layar. Untuk kenyamanan, jika `POWER` dikirim melalui scrcpy (melalui klik kanan atau<kbd>MOD</kbd>+<kbd>p</kbd>), itu akan memaksa untuk mematikan layar setelah penundaan kecil (atas dasar upaya terbaik).
Tombol fisik `POWER` masih akan menyebabkan layar dihidupkan.
Ini juga berguna untuk mencegah perangkat tidur:
```bash
scrcpy --turn-screen-off --stay-awake
scrcpy -Sw
```
#### Render frame kedaluwarsa
Secara default, untuk meminimalkan latensi, _scrcpy_ selalu menampilkan frame yang terakhir didekodekan tersedia, dan menghapus frame sebelumnya.
Untuk memaksa rendering semua frame (dengan kemungkinan peningkatan latensi), gunakan:
```bash
scrcpy --render-expired-frames
```
#### Tunjukkan sentuhan
Untuk presentasi, mungkin berguna untuk menunjukkan sentuhan fisik (pada perangkat fisik).
Android menyediakan fitur ini di _Opsi Pengembang_.
_Scrcpy_ menyediakan opsi untuk mengaktifkan fitur ini saat mulai dan mengembalikan nilai awal saat keluar:
```bash
scrcpy --show-touches
scrcpy -t
```
Perhatikan bahwa ini hanya menunjukkan sentuhan _fisik_ (dengan jari di perangkat).
#### Nonaktifkan screensaver
Secara default, scrcpy tidak mencegah screensaver berjalan di komputer.
Untuk menonaktifkannya:
```bash
scrcpy --disable-screensaver
```
### Kontrol masukan
#### Putar layar perangkat
Tekan <kbd>MOD</kbd>+<kbd>r</kbd> untuk beralih antara mode potret dan lanskap.
Perhatikan bahwa itu berputar hanya jika aplikasi di latar depan mendukung orientasi yang diminta.
#### Salin-tempel
Setiap kali papan klip Android berubah, secara otomatis disinkronkan ke papan klip komputer.
Apa saja <kbd>Ctrl</kbd> pintasan diteruskan ke perangkat. Khususnya:
- <kbd>Ctrl</kbd>+<kbd>c</kbd> biasanya salinan
- <kbd>Ctrl</kbd>+<kbd>x</kbd> biasanya memotong
- <kbd>Ctrl</kbd>+<kbd>v</kbd> biasanya menempel (setelah sinkronisasi papan klip komputer-ke-perangkat)
Ini biasanya berfungsi seperti yang Anda harapkan.
Perilaku sebenarnya tergantung pada aplikasi yang aktif. Sebagai contoh,
_Termux_ mengirim SIGINT ke <kbd>Ctrl</kbd>+<kbd>c</kbd> sebagai gantinya, dan _K-9 Mail_ membuat pesan baru.
Untuk menyalin, memotong dan menempel dalam kasus seperti itu (tetapi hanya didukung di Android> = 7):
- <kbd>MOD</kbd>+<kbd>v</kbd> injeksi `PASTE` (setelah sinkronisasi papan klip komputer-ke-perangkat)
Tambahan, <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd> memungkinkan untuk memasukkan teks papan klip komputer sebagai urutan peristiwa penting. Ini berguna ketika komponen tidak menerima penempelan teks (misalnya di _Termux_), tetapi dapat merusak konten non-ASCII.
**PERINGATAN:** Menempelkan papan klip komputer ke perangkat (baik melalui
<kbd>Ctrl</kbd>+<kbd>v</kbd> or <kbd>MOD</kbd>+<kbd>v</kbd>) menyalin konten ke clipboard perangkat. Akibatnya, aplikasi Android apa pun dapat membaca kontennya. Anda harus menghindari menempelkan konten sensitif (seperti kata sandi) seperti itu.
#### Cubit untuk memperbesar/memperkecil
Untuk mensimulasikan "cubit-untuk-memperbesar/memperkecil": <kbd>Ctrl</kbd>+_klik-dan-pindah_.
Lebih tepatnya, tahan <kbd>Ctrl</kbd> sambil menekan tombol klik kiri. Hingga tombol klik kiri dilepaskan, semua gerakan mouse berskala dan memutar konten (jika didukung oleh aplikasi) relatif ke tengah layar.
Secara konkret, scrcpy menghasilkan kejadian sentuh tambahan dari "jari virtual" di lokasi yang dibalik melalui bagian tengah layar.
#### Preferensi injeksi teks
Ada dua jenis [peristiwa][textevents] dihasilkan saat mengetik teks:
- _peristiwa penting_, menandakan bahwa tombol ditekan atau dilepaskan;
- _peristiwa teks_, menandakan bahwa teks telah dimasukkan.
Secara default, huruf dimasukkan menggunakan peristiwa kunci, sehingga keyboard berperilaku seperti yang diharapkan dalam game (biasanya untuk tombol WASD).
Tapi ini mungkin [menyebabkan masalah][prefertext]. Jika Anda mengalami masalah seperti itu, Anda dapat menghindarinya dengan:
```bash
scrcpy --prefer-text
```
(tapi ini akan merusak perilaku keyboard dalam game)
Secara default, menahan tombol akan menghasilkan peristiwa kunci yang berulang. Ini dapat menyebabkan masalah kinerja di beberapa game, di mana acara ini tidak berguna.
Untuk menghindari penerusan peristiwa penting yang berulang:
```bash
scrcpy --no-key-repeat
```
### Seret/jatuhkan file
#### Pasang APK
Untuk menginstal APK, seret & lepas file APK (diakhiri dengan `.apk`) ke jendela _scrcpy_.
Tidak ada umpan balik visual, log dicetak ke konsol.
#### Dorong file ke perangkat
Untuk mendorong file ke `/sdcard/` di perangkat, seret & jatuhkan file (non-APK) ke jendela _scrcpy_.
Tidak ada umpan balik visual, log dicetak ke konsol.
Direktori target dapat diubah saat mulai:
```bash
scrcpy --push-target /sdcard/foo/bar/
```
### Penerusan audio
Audio tidak diteruskan oleh _scrcpy_. Gunakan [sndcpy].
_Apri il [README](README.md) originale e sempre aggiornato._
# scrcpy (v1.19)
Questa applicazione fornisce la visualizzazione e il controllo dei dispositivi Android collegati via USB (o [via TCP/IP][article-tcpip]). Non richiede alcun accesso _root_.
Funziona su _GNU/Linux_, _Windows_ e _macOS_.
![screenshot](assets/screenshot-debian-600.jpg)
Si concentra su:
- **leggerezza** (nativo, mostra solo lo schermo del dispositivo)
- **prestazioni** (30~60fps)
- **qualità** (1920×1080 o superiore)
- **bassa latenza** ([35~70ms][lowlatency])
- **tempo di avvio basso** (~ 1secondo per visualizzare la prima immagine)
- **non invadenza** (nulla viene lasciato installato sul dispositivo)
Questo influisce sull'orientamento della registrazione.
La [finestra può anche essere ruotata](#rotazione) indipendentemente.
#### Codificatore
Alcuni dispositivi hanno più di un codificatore e alcuni di questi possono provocare problemi o crash. È possibile selezionare un encoder diverso:
```bash
scrcpy --encoder OMX.qcom.video.encoder.avc
```
Per elencare i codificatori disponibili puoi immettere un nome di codificatore non valido e l'errore mostrerà i codificatori disponibili:
```bash
scrcpy --encoder _
```
### Cattura
#### Registrazione
È possibile registrare lo schermo durante la trasmissione:
```bash
scrcpy --record file.mp4
scrcpy -r file.mkv
```
Per disabilitare la trasmissione durante la registrazione:
```bash
scrcpy --no-display --record file.mp4
scrcpy -Nr file.mkv
# interrompere la registrazione con Ctrl+C
```
I "fotogrammi saltati" sono registrati nonostante non siano mostrati in tempo reale (per motivi di prestazioni). I fotogrammi sono _datati_ sul dispositivo, così una [variazione di latenza dei pacchetti][packet delay variation] non impatta il file registrato.
Su Linux è possibile inviare il flusso video ad un dispositivo v4l2 loopback, cosicchè un dispositivo Android possa essere aperto come una webcam da qualsiasi strumento compatibile con v4l2.
Il modulo `v4l2loopback` deve essere installato:
```bash
sudo apt install v4l2loopback-dkms
```
Per creare un dispositvo v4l2:
```bash
sudo modprobe v4l2loopback
```
Questo creerà un nuovo dispositivo video in `/dev/videoN` dove `N` è un intero (più [opzioni](https://github.com/umlaeute/v4l2loopback#options) sono disponibili per crere più dispositivi o dispositivi con ID specifici).
Per elencare i dispositvi attivati:
```bash
# necessita del pacchetto v4l-utils
v4l2-ctl --list-devices
# semplice ma potrebbe essere sufficiente
ls /dev/video*
```
Per avviare scrcpy utilizzando un v4l2 sink:
```bash
scrcpy --v4l2-sink=/dev/videoN
scrcpy --v4l2-sink=/dev/videoN --no-display # disabilita la finestra di trasmissione
scrcpy --v4l2-sink=/dev/videoN -N # versione corta
```
(sostituisci `N` con l'ID del dispositivo, controlla con `ls /dev/video*`)
Una volta abilitato, puoi aprire il tuo flusso video con uno strumento compatibile con v4l2:
```bash
ffplay -i /dev/videoN
vlc v4l2:///dev/videoN # VLC potrebbe aggiungere del ritardo per il buffer
```
Per esempio potresti catturare il video in [OBS].
[OBS]: https://obsproject.com/
#### Buffering
È possibile aggiungere del buffer. Questo aumenta la latenza ma riduce il jitter (vedi [#2464]).
Se in `adb devices` sono listati più dispositivi, è necessario specificare il _seriale_:
```bash
scrcpy --serial 0123456789abcdef
scrcpy -s 0123456789abcdef # versione breve
```
Se il dispositivo è collegato mediante TCP/IP:
```bash
scrcpy --serial 192.168.0.1:5555
scrcpy -s 192.168.0.1:5555 # versione breve
```
Puoi avviare più istanze di _scrcpy_ per diversi dispositivi.
#### Avvio automativo alla connessione del dispositivo
Potresti usare [AutoAdb]:
```bash
autoadb scrcpy -s '{}'
```
[AutoAdb]: https://github.com/rom1v/autoadb
#### Tunnel SSH
Per connettersi a un dispositivo remoto è possibile collegare un client `adb` locale ad un server `adb` remoto (assunto che entrambi stiano usando la stessa versione del protocollo _adb_):
```bash
adb kill-server # termina il server adb locale su 5037
L'app può essere avviata direttamente a schermo intero:
```bash
scrcpy --fullscreen
scrcpy -f # versione breve
```
Lo schermo intero può anche essere attivato/disattivato con <kbd>MOD</kbd>+<kbd>f</kbd>.
#### Rotazione
La finestra può essere ruotata:
```bash
scrcpy --rotation 1
```
I valori possibili sono:
- `0`: nessuna rotazione
- `1`: 90 gradi antiorari
- `2`: 180 gradi
- `3`: 90 gradi orari
La rotazione può anche essere cambiata dinamicamente con <kbd>MOD</kbd>+<kbd>←</kbd>
_(sinistra)_ e <kbd>MOD</kbd>+<kbd>→</kbd>_(destra)_.
Notare che _scrcpy_ gestisce 3 diversi tipi di rotazione:
- <kbd>MOD</kbd>+<kbd>r</kbd> richiede al dispositvo di cambiare tra orientamento verticale (portrait) e orizzontale (landscape) (l'app in uso potrebbe rifiutarsi se non supporta l'orientamento richiesto).
- [`--lock-video-orientation`](#blocca-orientamento-del-video) cambia l'orientamento della trasmissione (l'orientamento del video inviato dal dispositivo al computer). Questo influenza la registrazione.
- `--rotation` (o <kbd>MOD</kbd>+<kbd>←</kbd>/<kbd>MOD</kbd>+<kbd>→</kbd>) ruota solo il contenuto della finestra. Questo influenza solo la visualizzazione, non la registrazione.
### Altre opzioni di trasmissione
#### "Sola lettura"
Per disabilitare i controlli (tutto ciò che può interagire col dispositivo: tasti di input, eventi del mouse, trascina e rilascia (drag&drop) file):
```bash
scrcpy --no-control
scrcpy -n
```
#### Schermo
Se sono disponibili più schermi, è possibile selezionare lo schermo da trasmettere:
```bash
scrcpy --display 1
```
La lista degli id schermo può essere ricavata da:
```bash
adb shell dumpsys display # cerca "mDisplayId=" nell'output
```
Lo schermo secondario potrebbe essere possibile controllarlo solo se il dispositivo esegue almeno Android 10 (in caso contrario è trasmesso in modalità sola lettura).
#### Mantenere sbloccato
Per evitare che il dispositivo si blocchi dopo un po' che il dispositivo è collegato:
```bash
scrcpy --stay-awake
scrcpy -w
```
Lo stato iniziale è ripristinato quando scrcpy viene chiuso.
#### Spegnere lo schermo
È possibile spegnere lo schermo del dispositivo durante la trasmissione con un'opzione da riga di comando:
```bash
scrcpy --turn-screen-off
scrcpy -S
```
Oppure premendo <kbd>MOD</kbd>+<kbd>o</kbd> in qualsiasi momento.
Per riaccenderlo premere <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>o</kbd>.
In Android il pulsante `POWER` (tasto di accensione) accende sempre lo schermo. Per comodità, se `POWER` è inviato via scrcpy (con click destro o con <kbd>MOD</kbd>+<kbd>p</kbd>), si forza il dispositivo a spegnere lo schermo dopo un piccolo ritardo (appena possibile).
Il pulsante fisico `POWER` continuerà ad accendere lo schermo normalmente.
Può anche essere utile evitare il blocco del dispositivo:
```bash
scrcpy --turn-screen-off --stay-awake
scrcpy -Sw
```
#### Mostrare i tocchi
Per le presentazioni può essere utile mostrare i tocchi fisici (sul dispositivo fisico).
Android fornisce questa funzionalità nelle _Opzioni sviluppatore_.
_Scrcpy_ fornisce un'opzione per abilitare questa funzionalità all'avvio e ripristinare il valore iniziale alla chiusura:
```bash
scrcpy --show-touches
scrcpy -t
```
Notare che mostra solo i tocchi _fisici_ (con le dita sul dispositivo).
#### Disabilitare il salvaschermo
In maniera predefinita scrcpy non previene l'attivazione del salvaschermo del computer.
Per disabilitarlo:
```bash
scrcpy --disable-screensaver
```
### Input di controlli
#### Rotazione dello schermo del dispostivo
Premere <kbd>MOD</kbd>+<kbd>r</kbd> per cambiare tra le modalità verticale (portrait) e orizzontale (landscape).
Notare che la rotazione avviene solo se l'applicazione in primo piano supporta l'orientamento richiesto.
#### Copia-incolla
Quando gli appunti di Android cambiano, essi vengono automaticamente sincronizzati con gli appunti del computer.
Qualsiasi scorciatoia <kbd>Ctrl</kbd> viene inoltrata al dispositivo. In particolare:
- <kbd>Ctrl</kbd>+<kbd>c</kbd> copia
- <kbd>Ctrl</kbd>+<kbd>x</kbd> taglia
- <kbd>Ctrl</kbd>+<kbd>v</kbd> incolla (dopo la sincronizzazione degli appunti da computer a dispositivo)
Questo solitamente funziona nella maniera più comune.
Il comportamento reale, però, dipende dall'applicazione attiva. Per esempio _Termux_ invia SIGINT con <kbd>Ctrl</kbd>+<kbd>c</kbd>, e _K-9 Mail_ compone un nuovo messaggio.
Per copiare, tagliare e incollare in questi casi (ma è solo supportato in Android >= 7):
- <kbd>MOD</kbd>+<kbd>c</kbd> inietta `COPY`
- <kbd>MOD</kbd>+<kbd>x</kbd> inietta `CUT`
- <kbd>MOD</kbd>+<kbd>v</kbd> inietta `PASTE` (dopo la sincronizzazione degli appunti da computer a dispositivo)
In aggiunta, <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd> permette l'iniezione del testo degli appunti del computer come una sequenza di eventi pressione dei tasti. Questo è utile quando il componente non accetta l'incollaggio di testo (per esempio in _Termux_), ma questo può rompere il contenuto non ASCII.
**AVVISO:** Incollare gli appunti del computer nel dispositivo (sia con <kbd>Ctrl</kbd>+<kbd>v</kbd> che con <kbd>MOD</kbd>+<kbd>v</kbd>) copia il contenuto negli appunti del dispositivo. Come conseguenza, qualsiasi applicazione Android potrebbe leggere il suo contenuto. Dovresti evitare di incollare contenuti sensibili (come password) in questa maniera.
Alcuni dispositivi non si comportano come aspettato quando si modificano gli appunti del dispositivo a livello di codice. L'opzione `--legacy-paste` è fornita per cambiare il comportamento di <kbd>Ctrl</kbd>+<kbd>v</kbd> and <kbd>MOD</kbd>+<kbd>v</kbd> in modo tale che anch'essi iniettino il testo gli appunti del computer come una sequenza di eventi pressione dei tasti (nella stessa maniera di <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd>).
#### Pizzica per zoomare (pinch-to-zoom)
Per simulare il "pizzica per zoomare": <kbd>Ctrl</kbd>+_click e trascina_.
Più precisamente, tieni premuto <kbd>Ctrl</kbd> mentre premi il pulsante sinistro. Finchè il pulsante non sarà rilasciato, tutti i movimenti del mouse ridimensioneranno e ruoteranno il contenuto (se supportato dall'applicazione) relativamente al centro dello schermo.
Concretamente scrcpy genera degli eventi di tocco addizionali di un "dito virtuale" nella posizione simmetricamente opposta rispetto al centro dello schermo.
#### Preferenze di iniezione del testo
Ci sono due tipi di [eventi][textevents] generati quando si scrive testo:
- _eventi di pressione_, segnalano che tasto è stato premuto o rilasciato;
- _eventi di testo_, segnalano che del testo è stato inserito.
In maniera predefinita le lettere sono "iniettate" usando gli eventi di pressione, in maniera tale che la tastiera si comporti come aspettato nei giochi (come accade solitamente per i tasti WASD).
Questo, però, può [causare problemi][prefertext]. Se incontri un problema del genere, puoi evitarlo con:
```bash
scrcpy --prefer-text
```
(ma questo romperà il normale funzionamento della tastiera nei giochi)
In maniera predefinita tenere premuto un tasto genera una ripetizione degli eventi di pressione di tale tasto. Questo può creare problemi di performance in alcuni giochi, dove questi eventi sono inutilizzati.
Per prevenire l'inoltro ripetuto degli eventi di pressione:
```bash
scrcpy --no-key-repeat
```
#### Click destro e click centrale
In maniera predefinita, click destro aziona BACK (indietro) e il click centrale aziona HOME. Per disabilitare queste scorciatoie e, invece, inviare i click al dispositivo:
```bash
scrcpy --forward-all-clicks
```
### Rilascio di file
#### Installare APK
Per installare un APK, trascina e rilascia un file APK (finisce con `.apk`) nella finestra di _scrcpy_.
Non c'è alcuna risposta visiva, un log è stampato nella console.
#### Trasferimento di file verso il dispositivo
Per trasferire un file in `/sdcard/Download` del dispositivo trascina e rilascia un file (non APK) nella finestra di _scrcpy_.
Non c'è alcuna risposta visiva, un log è stampato nella console.
La cartella di destinazione può essere cambiata all'avvio:
```bash
scrcpy --push-target=/sdcard/Movies/
```
### Inoltro dell'audio
L'audio non è inoltrato da _scrcpy_. Usa [sndcpy].
Nella lista seguente, <kbd>MOD</kbd> è il modificatore delle scorciatoie. In maniera predefinita è <kbd>Alt</kbd> (sinistro) o <kbd>Super</kbd> (sinistro).
Può essere cambiato usando `--shortcut-mod`. I tasti possibili sono `lctrl`, `rctrl`, `lalt`, `ralt`, `lsuper` and `rsuper` (`l` significa sinistro e `r` significa destro). Per esempio:
```bash
# usa ctrl destro per le scorciatoie
scrcpy --shortcut-mod=rctrl
# use sia "ctrl sinistro"+"alt sinistro" che "super sinistro" per le scorciatoie
scrcpy --shortcut-mod=lctrl+lalt,lsuper
```
_<kbd>[Super]</kbd> è il pulsante <kbd>Windows</kbd> o <kbd>Cmd</kbd>._
<!-- https://en.wikipedia.org/wiki/Super_key_(keyboard_button) è la pagina originale di Wikipedia inglese, l'ho sostituita con una simile in quello italiano -->
| Copia negli appunti⁴ | <kbd>MOD</kbd>+<kbd>c</kbd>
| Taglia negli appunti⁴ | <kbd>MOD</kbd>+<kbd>x</kbd>
| Sincronizza gli appunti e incolla⁴ | <kbd>MOD</kbd>+<kbd>v</kbd>
| Inietta il testo degli appunti del computer | <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd>
| Abilita/Disabilita il contatore FPS (su stdout) | <kbd>MOD</kbd>+<kbd>i</kbd>
| Pizzica per zoomare | <kbd>Ctrl</kbd>+_click e trascina_
_¹Doppio click sui bordi neri per rimuoverli._
_²Il tasto destro accende lo schermo se era spento, preme BACK in caso contrario._
_³4° e 5° pulsante del mouse, se il tuo mouse ne dispone._
_⁴Solo in Android >= 7._
Le scorciatoie con pulsanti ripetuti sono eseguite rilasciando e premendo il pulsante una seconda volta. Per esempio, per eseguire "Espandi il pannello delle impostazioni":
1. Premi e tieni premuto <kbd>MOD</kbd>.
2. Poi premi due volte <kbd>n</kbd>.
3. Infine rilascia <kbd>MOD</kbd>.
Tutte le scorciatoie <kbd>Ctrl</kbd>+_tasto_ sono inoltrate al dispositivo, così sono gestite dall'applicazione attiva.
## Path personalizzati
Per utilizzare dei binari _adb_ specifici, configura il suo path nella variabile d'ambente `ADB`:
```bash
ADB=/percorso/per/adb scrcpy
```
Per sovrascrivere il percorso del file `scrcpy-server`, configura il percorso in `SCRCPY_SERVER_PATH`.
## Perchè _scrcpy_?
Un collega mi ha sfidato a trovare un nome tanto impronunciabile quanto [gnirehtet].
[`strcpy`] copia una **str**ing (stringa); `scrcpy` copia uno **scr**een (schermo).
윈도우 상에서, 간단하게 설치하기 위해 종속성이 있는 사전 구축된 아카이브가 제공됩니다 (`adb` 포함) :
해당 파일은 Readme원본 링크를 통해서 다운로드가 가능합니다.
- [README](README.md#windows)
[어플을 직접 설치][BUILD] 할 수도 있습니다.
### macOS (맥 OS)
이 어플리케이션은 아래 사항을 따라 설치한다면 [Homebrew] 에서도 사용 가능합니다 :
[Homebrew]: https://brew.sh/
```bash
brew install scrcpy
```
`PATH` 로부터 접근 가능한 `adb` 가 필요합니다. 아직 설치하지 않았다면 다음을 따라 설치해야 합니다 :
```bash
brew cask install android-platform-tools
```
[어플을 직접 설치][BUILD] 할 수도 있습니다.
## 실행
안드로이드 디바이스를 연결하고 실행하십시오:
```bash
scrcpy
```
다음과 같이 명령창 옵션 기능도 제공합니다.
```bash
scrcpy --help
```
## 기능
### 캡쳐 환경 설정
### 사이즈 재정의
가끔씩 성능을 향상시키기위해 안드로이드 디바이스를 낮은 해상도에서 미러링하는 것이 유용할 때도 있습니다.
너비와 높이를 제한하기 위해 특정 값으로 지정할 수 있습니다 (e.g. 1024) :
```bash
scrcpy --max-size 1024
scrcpy -m 1024 # 축약 버전
```
이 외의 크기도 디바이스의 가로 세로 비율이 유지된 상태에서 계산됩니다.
이러한 방식으로 디바이스 상에서 1920×1080 는 모니터 상에서1024×576로 미러링될 것 입니다.
### bit-rate 변경
기본 bit-rate 는 8 Mbps입니다. 비디오 bit-rate 를 변경하기 위해선 다음과 같이 입력하십시오 (e.g. 2 Mbps로 변경):
```bash
scrcpy --bit-rate 2M
scrcpy -b 2M # 축약 버전
```
### 프레임 비율 제한
안드로이드 버전 10이상의 디바이스에서는, 다음의 명령어로 캡쳐 화면의 프레임 비율을 제한할 수 있습니다:
```bash
scrcpy --max-fps 15
```
### Crop (잘라내기)
디바이스 화면은 화면의 일부만 미러링하기 위해 잘라질 것입니다.
예를 들어, *Oculus Go* 의 한 쪽 눈만 미러링할 때 유용합니다 :
```bash
scrcpy --crop 1224:1440:0:0 # 1224x1440 at offset (0,0)
scrcpy -c 1224:1440:0:0 # 축약 버전
```
만약 `--max-size` 도 지정하는 경우, 잘라낸 다음에 재정의된 크기가 적용될 것입니다.
### 화면 녹화
미러링하는 동안 화면 녹화를 할 수 있습니다 :
```bash
scrcpy --record file.mp4
scrcpy -r file.mkv
```
녹화하는 동안 미러링을 멈출 수 있습니다 :
```bash
scrcpy --no-display --record file.mp4
scrcpy -Nr file.mkv
# Ctrl+C 로 녹화를 중단할 수 있습니다.
# 윈도우 상에서 Ctrl+C 는 정상정으로 종료되지 않을 수 있으므로, 디바이스 연결을 해제하십시오.
```
"skipped frames" 은 모니터 화면에 보여지지 않았지만 녹화되었습니다 ( 성능 문제로 인해 ). 프레임은 디바이스 상에서 _타임 스탬프 ( 어느 시점에 데이터가 존재했다는 사실을 증명하기 위해 특정 위치에 시각을 표시 )_ 되었으므로, [packet delay
scrcpy --lock-video-orientation=3 # 90° sentido de las agujas del reloj
```
Esto afecta la rotación de la grabación.
La [ventana también puede ser rotada](#rotación) independientemente.
#### Codificador
Algunos dispositivos pueden tener más de una rotación, y algunos pueden causar problemas o errores. Es posible seleccionar un codificador diferente:
```bash
scrcpy --encoder OMX.qcom.video.encoder.avc
```
Para listar los codificadores disponibles, puedes pasar un nombre de codificador inválido, el error te dará los codificadores disponibles:
```bash
scrcpy --encoder _
```
### Capturas y grabaciones
#### Grabación
Es posible grabar la pantalla mientras se transmite:
```bash
scrcpy --record file.mp4
scrcpy -r file.mkv
```
Para grabar sin transmitir la pantalla:
```bash
scrcpy --no-display --record file.mp4
scrcpy -Nr file.mkv
# interrumpe la grabación con Ctrl+C
```
Los "skipped frames" son grabados, incluso si no se mostrados en tiempo real (por razones de desempeño). Los frames tienen _marcas de tiempo_ en el dispositivo, por lo que el "[packet delay
Si hay muchos dispositivos listados en `adb devices`, será necesario especificar el _número de serie_:
```bash
scrcpy --serial 0123456789abcdef
scrcpy -s 0123456789abcdef # versión breve
```
Si el dispositivo está conectado por TCP/IP:
```bash
scrcpy --serial 192.168.0.1:5555
scrcpy -s 192.168.0.1:5555 # versión breve
```
Puedes iniciar múltiples instancias de _scrcpy_ para múltiples dispositivos.
#### Iniciar automáticamente al detectar dispositivo
Puedes utilizar [AutoAdb]:
```bash
autoadb scrcpy -s '{}'
```
[AutoAdb]: https://github.com/rom1v/autoadb
#### Túneles
Para conectarse a un dispositivo remoto, es posible conectar un cliente local `adb` a un servidor remoto `adb` (siempre y cuando utilicen la misma versión de protocolos _adb_).
##### Servidor ADB remoto
Para conectarse a un servidor ADB remoto, haz que el servidor escuche en todas las interfaces:
```bash
adb kill-server
adb -a nodaemon server start
# conserva este servidor abierto
```
**Advertencia: todas las comunicaciones entre los clientes y el servidor ADB están desencriptadas.**
Supondremos que este servidor se puede acceder desde 192.168.1.2. Entonces, desde otra
terminal, corré scrcpy:
```bash
export ADB_SERVER_SOCKET=tcp:192.168.1.2:5037
scrcpy --tunnel-host=192.168.1.2
```
Por default, scrcpy usa el puerto local que se usó para establecer el tunel
`adb forward` (típicamente `27183`, vea `--port`). También es posible forzar un
puerto diferente (puede resultar útil en situaciones más complejas, donde haya
múltiples redirecciones):
```
scrcpy --tunnel-port=1234
```
##### Túnel SSH
Para comunicarse con un servidor ADB remoto de forma segura, es preferible usar un túnel SSH.
Primero, asegurate que el servidor ADB está corriendo en la computadora remota:
Para mantener la ventana de scrcpy siempre adelante:
```bash
scrcpy --always-on-top
```
#### Pantalla completa
La aplicación puede ser iniciada en pantalla completa:
```bash
scrcpy --fullscreen
scrcpy -f # versión breve
```
Puede entrar y salir de la pantalla completa con la combinación <kbd>MOD</kbd>+<kbd>f</kbd>.
#### Rotación
Se puede rotar la ventana:
```bash
scrcpy --rotation 1
```
Los posibles valores son:
- `0`: sin rotación
- `1`: 90 grados contrarreloj
- `2`: 180 grados
- `3`: 90 grados en sentido de las agujas del reloj
La rotación también puede ser modificada con la combinación de teclas <kbd>MOD</kbd>+<kbd>←</kbd>_(izquierda)_ y <kbd>MOD</kbd>+<kbd>→</kbd>_(derecha)_.
Nótese que _scrcpy_ maneja 3 diferentes rotaciones:
- <kbd>MOD</kbd>+<kbd>r</kbd> solicita al dispositivo cambiar entre vertical y horizontal (la aplicación en uso puede rechazarlo si no soporta la orientación solicitada).
- [`--lock-video-orientation`](#fijar-la-rotación-del-video) cambia la rotación de la transmisión (la orientación del video enviado a la PC). Esto afecta a la grabación.
- `--rotation` (o <kbd>MOD</kbd>+<kbd>←</kbd>/<kbd>MOD</kbd>+<kbd>→</kbd>) rota solo el contenido de la imagen. Esto solo afecta a la imagen mostrada, no a la grabación.
### Otras opciones
#### Solo lectura ("Read-only")
Para deshabilitar los controles (todo lo que interactúe con el dispositivo: eventos del teclado, eventos del mouse, arrastrar y soltar archivos):
```bash
scrcpy --no-control
scrcpy -n # versión breve
```
#### Pantalla
Si múltiples pantallas están disponibles, es posible elegir cual transmitir:
```bash
scrcpy --display 1
```
Los ids de las pantallas se pueden obtener con el siguiente comando:
```bash
adb shell dumpsys display # busque "mDisplayId=" en la respuesta
```
La segunda pantalla solo puede ser manejada si el dispositivo cuenta con Android 10 (en caso contrario será transmitida en el modo solo lectura).
#### Permanecer activo
Para evitar que el dispositivo descanse después de un tiempo mientras está conectado:
```bash
scrcpy --stay-awake
scrcpy -w # versión breve
```
La configuración original se restaura al cerrar scrcpy.
#### Apagar la pantalla
Es posible apagar la pantalla mientras se transmite al iniciar con el siguiente comando:
```bash
scrcpy --turn-screen-off
scrcpy -S # versión breve
```
O presionando <kbd>MOD</kbd>+<kbd>o</kbd> en cualquier momento.
Para volver a prenderla, presione <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>o</kbd>.
En Android, el botón de `POWER` siempre prende la pantalla. Por conveniencia, si `POWER` es enviado vía scrcpy (con click-derecho o <kbd>MOD</kbd>+<kbd>p</kbd>), esto forzará a apagar la pantalla con un poco de atraso (en la mejor de las situaciones). El botón físico `POWER` seguirá prendiendo la pantalla.
También puede resultar útil para evitar que el dispositivo entre en inactividad:
```bash
scrcpy --turn-screen-off --stay-awake
scrcpy -Sw # versión breve
```
#### Apagar al cerrar la aplicación
Para apagar la pantalla del dispositivo al cerrar scrcpy:
```bash
scrcpy --power-off-on-close
```
#### Mostrar clicks
Para presentaciones, puede resultar útil mostrar los clicks físicos (en el dispositivo físicamente).
Android provee esta opción en _Opciones para desarrolladores_.
_Scrcpy_ provee una opción para habilitar esta función al iniciar la aplicación y restaurar el valor original al salir:
```bash
scrcpy --show-touches
scrcpy -t # versión breve
```
Nótese que solo muestra los clicks _físicos_ (con el dedo en el dispositivo).
#### Desactivar protector de pantalla
Por defecto, scrcpy no evita que el protector de pantalla se active en la computadora.
Para deshabilitarlo:
```bash
scrcpy --disable-screensaver
```
### Control
#### Rotar pantalla del dispositivo
Presione <kbd>MOD</kbd>+<kbd>r</kbd> para cambiar entre posición vertical y horizontal.
Nótese que solo rotará si la aplicación activa soporta la orientación solicitada.
#### Copiar y pegar
Cuando que el portapapeles de Android cambia, automáticamente se sincroniza al portapapeles de la computadora.
Cualquier shortcut con <kbd>Ctrl</kbd> es enviado al dispositivo. En particular:
- <kbd>Ctrl</kbd>+<kbd>c</kbd> normalmente copia
- <kbd>Ctrl</kbd>+<kbd>x</kbd> normalmente corta
- <kbd>Ctrl</kbd>+<kbd>v</kbd> normalmente pega (después de la sincronización de portapapeles entre la computadora y el dispositivo)
Esto normalmente funciona como es esperado.
Sin embargo, este comportamiento depende de la aplicación en uso. Por ejemplo, _Termux_ envía SIGINT con <kbd>Ctrl</kbd>+<kbd>c</kbd>, y _K-9 Mail_ crea un nuevo mensaje.
Para copiar, cortar y pegar, en tales casos (solo soportado en Android >= 7):
- <kbd>MOD</kbd>+<kbd>c</kbd> inyecta `COPY`
- <kbd>MOD</kbd>+<kbd>x</kbd> inyecta `CUT`
- <kbd>MOD</kbd>+<kbd>v</kbd> inyecta `PASTE` (después de la sincronización de portapapeles entre la computadora y el dispositivo)
Además, <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd> permite inyectar el texto en el portapapeles de la computadora como una secuencia de teclas. Esto es útil cuando el componente no acepta pegado de texto (por ejemplo en _Termux_), pero puede romper caracteres no pertenecientes a ASCII.
**AVISO:** Pegar de la computadora al dispositivo (tanto con <kbd>Ctrl</kbd>+<kbd>v</kbd> o <kbd>MOD</kbd>+<kbd>v</kbd>) copia el contenido al portapapeles del dispositivo. Como consecuencia, cualquier aplicación de Android puede leer su contenido. Debería evitar pegar contenido sensible (como contraseñas) de esta forma.
Algunos dispositivos no se comportan como es esperado al establecer el portapapeles programáticamente. La opción `--legacy-paste` está disponible para cambiar el comportamiento de <kbd>Ctrl</kbd>+<kbd>v</kbd> y <kbd>MOD</kbd>+<kbd>v</kbd> para que también inyecten el texto del portapapeles de la computadora como una secuencia de teclas (de la misma forma que <kbd>MOD</kbd>+<kbd>Shift</kbd>+<kbd>v</kbd>).
Para deshabilitar la auto-sincronización del portapapeles, use `--no-clipboard-autosync`.
#### Pellizcar para zoom
Para simular "pinch-to-zoom": <kbd>Ctrl</kbd>+_click-y-mover_.
Más precisamente, mantén <kbd>Ctrl</kbd> mientras presionas botón izquierdo. Hasta que no se suelte el botón, todos los movimientos del mouse cambiarán el tamaño y rotación del contenido (si es soportado por la app en uso) respecto al centro de la pantalla.
Concretamente, scrcpy genera clicks adicionales con un "dedo virtual" en la posición invertida respecto al centro de la pantalla.
#### Emular teclado físico (HID)
Por default, scrcpy usa el sistema de Android para la injección de teclas o texto:
funciona en todas partes, pero está limitado a ASCII.
En Linux, scrcpy puede emular un teclado USB físico en Android para proveer
una mejor experiencia al enviar _inputs_ (usando [USB HID vía AOAv2][hid-aoav2]):
deshabilita el teclado virtual y funciona para todos los caracteres y IME.
Por defecto, mantener una tecla presionada genera múltiples _key events_. Esto puede
causar problemas de desempeño en algunos juegos, donde estos eventos no tienen sentido de todos modos.
Para evitar enviar _key events_ repetidos:
```bash
scrcpy --no-key-repeat
```
Estas opciones no tienen efecto en los teclados HID (Android maneja directamente
las repeticiones de teclas en este modo)
#### Botón derecho y botón del medio
Por defecto, botón derecho ejecuta RETROCEDER (o ENCENDIDO) y botón del medio INICIO. Para inhabilitar estos atajos y enviar los clicks al dispositivo:
```bash
scrcpy --forward-all-clicks
```
### Arrastrar y soltar archivos
#### Instalar APKs
Para instalar un APK, arrastre y suelte el archivo APK (terminado en `.apk`) a la ventana de _scrcpy_.
No hay respuesta visual, un mensaje se escribirá en la consola.
#### Enviar archivos al dispositivo
Para enviar un archivo a `/sdcard/Download/` en el dispositivo, arrastre y suelte
un archivo (no APK) a la ventana de _scrcpy_.
No hay ninguna respuesta visual, un mensaje se escribirá en la consola.
El directorio de destino puede ser modificado al iniciar:
En la siguiente lista, <kbd>MOD</kbd> es el atajo modificador. Por defecto es <kbd>Alt</kbd> (izquierdo) o <kbd>Super</kbd> (izquierdo).
Se puede modificar usando `--shortcut-mod`. Las posibles teclas son `lctrl` (izquierdo), `rctrl` (derecho), `lalt` (izquierdo), `ralt` (derecho), `lsuper` (izquierdo) y `rsuper` (derecho). Por ejemplo:
```bash
# use RCtrl para los atajos
scrcpy --shortcut-mod=rctrl
# use tanto LCtrl+LAlt o LSuper para los atajos
scrcpy --shortcut-mod=lctrl+lalt,lsuper
```
_<kbd>[Super]</kbd> es generalmente la tecla <kbd>Windows</kbd> o <kbd>Cmd</kbd>._
Use a specific MediaCodec audio encoder (depending on the codec provided by \fB\-\-audio\-codec\fR).
The available encoders can be listed by \fB\-\-list\-encoders\fR.
.TP
.BI"\-\-audio\-source "source
Select the audio source (output or mic).
Default is output.
.TP
.BI"\-\-audio\-output\-buffer "ms
Configure the size of the SDL audio output buffer (in milliseconds).
If you get "robotic" audio playback, you should test with a higher value (10). Do not change this setting otherwise.
Default is 5.
.TP
.BI"\-b, \-\-video\-bit\-rate "value
Encode the video at the given bit rate, expressed in bits/s. Unit suffixes are supported: '\fBK\fR' (x1000) and '\fBM\fR' (x1000000).
Default is 8M (8000000).
.TP
.BI"\-\-camera\-ar "ar
Select the camera size by its aspect ratio (+/- 10%).
Possible values are "sensor" (use the camera sensor aspect ratio), "\fInum\fR:\fIden\fR" (e.g. "4:3") and "\fIvalue\fR" (e.g. "1.6").
.TP
.B\-\-camera\-high\-speed
Enable high-speed camera capture mode.
This mode is restricted to specific resolutions and frame rates, listed by \fB\-\-list\-camera\-sizes\fR.
.TP
.BI"\-\-camera\-id "id
Specify the device camera id to mirror.
The available camera ids can be listed by \fB\-\-list\-cameras\fR.
.TP
.BI"\-\-camera\-facing "facing
Select the device camera by its facing direction.
Possible values are "front", "back" and "external".
.TP
.BI"\-\-camera\-fps "fps
Specify the camera capture frame rate.
If not specified, Android's default frame rate (30 fps) is used.
.TP
.BI"\-\-camera\-size "width\fRx\fIheight
Specify an explicit camera capture size.
.TP
.BI"\-\-crop "width\fR:\fIheight\fR:\fIx\fR:\fIy
@ -50,23 +124,30 @@ Use USB device (if there is exactly one, like adb -d).
Also see \fB\-e\fR (\fB\-\-select\-tcpip\fR).
.TP
.BI"\-\-disable-screensaver"
.BI"\-\-disable\-screensaver"
Disable screensaver while scrcpy is running.
.TP
.BI"\-\-display " id
Specify the display id to mirror.
.BI"\-\-display\-buffer " ms
Add a buffering delay (in milliseconds) before displaying. This increases latency to compensate for jitter.
The list of possible display ids can be listed by "adb shell dumpsys display"
(search "mDisplayId=" in the output).
Default is 0 (no buffering).
.TP
.BI"\-\-display\-id "id
Specify the device display id to mirror.
The available display ids can be listed by \fB\-\-list\-displays\fR.
Default is 0.
.TP
.BI"\-\-display\-bufferms
Add a buffering delay (in milliseconds) before displaying. This increases latency to compensate for jitter.
.BI"\-\-display\-orientation "value
Set the initial display orientation.
Default is 0 (no buffering).
Possible values are 0, 90, 180, 270, flip0, flip90, flip180 and flip270. The number represents the clockwise rotation in degrees; the "flip" keyword applies a horizontal flip before the rotation.
Default is 0.
.TP
.B\-e,\-\-select\-tcpip
@ -75,8 +156,8 @@ Use TCP/IP device (if there is exactly one, like adb -e).
Also see \fB\-d\fR (\fB\-\-select\-usb\fR).
.TP
.BI "\-\-encoder "name
Use a specific MediaCodec encoder (must be a H.264 encoder).
.B\-f,\-\-fullscreen
Start in fullscreen.
.TP
.B\-\-force\-adb\-forward
@ -86,29 +167,36 @@ Do not attempt to use "adb reverse" to connect to the device.
.B\-\-forward\-all\-clicks
By default, right-click triggers BACK (or POWER on) and middle-click triggers HOME. This option disables these shortcuts and forward the clicks to the device instead.
.TP
.B\-f,\-\-fullscreen
Start in fullscreen.
.TP
.B\-h,\-\-help
Print this help.
.TP
.B\-K,\-\-hid\-keyboard
Simulate a physical keyboard by using HID over AOAv2.
.B\-K
Same as \fB\-\-keyboard=uhid\fR.
.TP
.BI"\-\-keyboard "mode
Select how to send keyboard inputs to the device.
This provides a better experience for IME users, and allows to generate non-ASCII characters, contrary to the default injection method.
Possible values are "disabled", "sdk", "uhid" and "aoa":
It may only work over USB.
- "disabled" does not send keyboard inputs to the device.
- "sdk" uses the Android system API to deliver keyboard events to applications.
- "uhid" simulates a physical HID keyboard using the Linux HID kernel module on the device.
- "aoa" simulates a physical HID keyboard using the AOAv2 protocol. It may only work over USB.
The keyboard layout must be configured (once and for all) on the device, via Settings -> System -> Languages and input -> Physical keyboard. This settings page can be started directly:
For "uhid" and "aoa", the keyboard layout must be configured (once and for all) on the device, via Settings -> System -> Languages and input -> Physical keyboard. This settings page can be started directly using the shortcut MOD+k (except in OTG mode), or by executing:
adb shell am start -a android.settings.HARD_KEYBOARD_SETTINGS
However, the option is only available when the HID keyboard is enabled (or a physical keyboard is connected).
This option is only available when the HID keyboard is enabled (or a physical keyboard is connected).
Also see \fB\-\-hid\-mouse\fR.
Also see \fB\-\-mouse\fR.
.TP
.B\-\-kill\-adb\-on\-close
Kill adb when scrcpy terminates.
.TP
.B\-\-legacy\-paste
@ -117,16 +205,30 @@ Inject computer clipboard text as a sequence of key events on Ctrl+v (like MOD+S
This is a workaround for some devices not behaving as expected when setting the device clipboard programmatically.
.TP
.BI "\-\-lock\-video\-orientation[=value]
Lock video orientation to \fIvalue\fR. Possible values are "unlocked", "initial" (locked to the initial orientation), 0, 1, 2 and 3. Natural device orientation is 0, and each increment adds a 90 degrees rotation counterclockwise.
.B\-\-list\-camera\-sizes
List the valid camera capture sizes.
Default is "unlocked".
.TP
.B\-\-list\-cameras
List cameras available on the device.
Passing the option without argument is equivalent to passing "initial".
.TP
.B\-\-list\-encoders
List video and audio encoders available on the device.
.TP
.BI"\-\-max\-fps "value
Limit the framerate of screen capture (officially supported since Android 10, but may work on earlier versions).
.B\-\-list\-displays
List displays available on the device.
.TP
\fB\-\-lock\-video\-orientation\fR[=\fIvalue\fR]
Lock capture video orientation to \fIvalue\fR.
Possible values are "unlocked", "initial" (locked to the initial orientation), 0, 90, 180, and 270. The values represent the clockwise rotation from the natural device orientation, in degrees.
Default is "unlocked".
Passing the option without argument is equivalent to passing "initial".
.TP
.BI"\-m, \-\-max\-size "value
@ -135,16 +237,46 @@ Limit both the width and height of the video to \fIvalue\fR. The other dimension
Default is 0 (unlimited).
.TP
.B\-M,\-\-hid\-mouse
Simulate a physical mouse by using HID over AOAv2.
.B\-M
Same as \fB\-\-mouse=uhid\fR.
.TP
.BI"\-\-max\-fps "value
Limit the framerate of screen capture (officially supported since Android 10, but may work on earlier versions).
.TP
.BI"\-\-mouse "mode
Select how to send mouse inputs to the device.
Possible values are "disabled", "sdk", "uhid" and "aoa":
- "disabled" does not send mouse inputs to the device.
- "sdk" uses the Android system API to deliver mouse events to applications.
- "uhid" simulates a physical HID mouse using the Linux HID kernel module on the device.
- "aoa" simulates a physical mouse using the AOAv2 protocol. It may only work over USB.
In this mode, the computer mouse is captured to control the device directly (relative mouse mode).
In "uhid" and "aoa" modes, the computer mouse is captured to control the device directly (relative mouse mode).
LAlt, LSuper or RSuper toggle the capture mode, to give control of the mouse back to the computer.
It may only work over USB.
Also see \fB\-\-keyboard\fR.
.TP
.B\-n,\-\-no\-control
Disable device control (mirror the device in read\-only).
Also see \fB\-\-hid\-keyboard\fR.
.TP
.B\-N,\-\-no\-playback
Disable video and audio playback on the computer (equivalent to \fB\-\-no\-video\-playback \-\-no\-audio\-playback\fR).
.TP
.B\-\-no\-audio
Disable audio forwarding.
.TP
.B\-\-no\-audio\-playback
Disable audio playback on the computer.
.TP
.B\-\-no\-cleanup
@ -164,14 +296,6 @@ By default, on MediaCodec error, scrcpy automatically tries again with a lower d
This option disables this behavior.
.TP
.B\-n,\-\-no\-control
Disable device control (mirror the device in read\-only).
.TP
.B\-N,\-\-no\-display
Do not display device (only when screen recording is enabled).
.TP
.B\-\-no\-key\-repeat
Do not forward repeated key events when a key is held down.
@ -180,6 +304,22 @@ Do not forward repeated key events when a key is held down.
.B\-\-no\-mipmaps
If the renderer is OpenGL 3.0+ or OpenGL ES 2.0+, then mipmaps are automatically generated to improve downscaling quality. This option disables the generation of mipmaps.
.TP
.B\-\-no\-power\-on
Do not power on the device on start.
.TP
.B\-\-no\-video
Disable video forwarding.
.TP
.B\-\-no\-video\-playback
Disable video playback on the computer.
.TP
.BI"\-\-orientation "value
Same as --display-orientation=value --record-orientation=value.
.TP
.B\-\-otg
Run in OTG mode: simulate physical keyboard and mouse, as if the computer keyboard and mouse were plugged directly to the device via an OTG cable.
@ -195,11 +335,21 @@ It may only work over USB.
See \fB\-\-hid\-keyboard\fR and \fB\-\-hid\-mouse\fR.
.TP
.BI"\-p, \-\-port "port[:port]
.BI"\-p, \-\-port "port\fR[:\fIport\fR]
Set the TCP port (range) used by the client to listen.
Default is 27183:27199.
.TP
\fB\-\-pause\-on\-exit\fR[=\fImode\fR]
Configure pause on exit. Possible values are "true" (always pause on exit), "false" (never pause on exit) and "if-error" (pause only if an error occured).
This is useful to prevent the terminal window from automatically closing, so that error messages can be read.
Default is "false".
Passing the option without argument is equivalent to passing "true".
.TP
.B\-\-power\-off\-on\-close
Turn the device screen off when closing scrcpy.
@ -221,10 +371,6 @@ Set the target directory for pushing files to the device by drag & drop. It is p
Default is "/sdcard/Download/".
.TP
.B\-\-raw\-key\-events
Inject key events for all input keys, and ignore text events.
.TP
.BI"\-r, \-\-record "file
Record screen to
@ -232,11 +378,23 @@ Record screen to
The format is determined by the
.B\-\-record\-format
option if set, or by the file extension (.mp4 or .mkv).
option if set, or by the file extension.
.TP
.B\-\-raw\-key\-events
Inject key events for all input keys, and ignore text events.
.TP
.BI"\-\-record\-format "format
Force recording format (either mp4 or mkv).
Force recording format (mp4, mkv, m4a, mka, opus, aac, flac or wav).
.TP
.BI"\-\-record\-orientation "value
Set the record orientation.
Possible values are 0, 90, 180 and 270. The number represents the clockwise rotation in degrees.
Default is 0.
.TP
.BI"\-\-render\-driver "name
@ -244,19 +402,22 @@ Request SDL to use the given render driver (this is just a hint).
Supported names are currently "direct3d", "opengl", "opengles2", "opengles", "metal" and "software".
.URhttps://wiki.libsdl.org/SDL_HINT_RENDER_DRIVER
.UE
<https://wiki.libsdl.org/SDL_HINT_RENDER_DRIVER>
.TP
.BI "\-\-rotation "value
Set the initial display rotation. Possibles values are 0, 1, 2 and 3. Each increment adds a 90 degrees rotation counterclockwise.
.B\-\-require\-audio
By default, scrcpy mirrors only the video if audio capture fails on the device. This option makes scrcpy fail if audio is enabled but does not work.
.TP
.BI"\-s, \-\-serial "number
The device serial number. Mandatory only if several devices are connected to adb.
.TP
.BI"\-\-shortcut\-mod "key[+...]][,...]
.B\-S,\-\-turn\-screen\-off
Turn the device screen off immediately.
.TP
.BI"\-\-shortcut\-mod "key\fR[+...]][,...]
Specify the modifiers to use for scrcpy shortcuts. Possible keys are "lctrl", "rctrl", "lalt", "ralt", "lsuper" and "rsuper".
A shortcut can consist in several keys, separated by '+'. Several shortcuts can be specified, separated by ','.
@ -266,35 +427,45 @@ For example, to use either LCtrl+LAlt or LSuper for scrcpy shortcuts, pass "lctr
Default is "lalt,lsuper" (left-Alt or left-Super).
.TP
.BI"\-\-tcpip[=ip[:port]]
.B\-t,\-\-show\-touches
Enable "show touches" on start, restore the initial value on exit.
It only shows physical touches (not clicks from scrcpy).
.TP
.BI"\-\-tcpip\fR[=\fIip\fR[:\fIport\fR]]
Configure and reconnect the device over TCP/IP.
If a destination address is provided, then scrcpy connects to this address before starting. The device must listen on the given TCP port (default is 5555).
If no destination address is provided, then scrcpy attempts to find the IP address of the current device (typically connected over USB), enables TCP/IP mode, then connects to this address before starting.
.TP
.B\-S,\-\-turn\-screen\-off
Turn the device screen off immediately.
If no destination address is provided, then scrcpy attempts to find the IP address and adb port of the current device (typically connected over USB), enables TCP/IP mode if necessary, then connects to this address before starting.
.TP
.B\-t,\-\-show\-touches
Enable "show touches" on start, restore the initial value on exit.
It only shows physical touches (not clicks from scrcpy).
.BI"\-\-time\-limit "seconds
Set the maximum mirroring time, in seconds.
.TP
.BI"\-\-tunnel\-host "ip
Set the IP address of the adb tunnel to reach the scrcpy server. This option automatically enables --force-adb-forward.
Set the IP address of the adb tunnel to reach the scrcpy server. This option automatically enables \fB\-\-force\-adb\-forward\fR.
Default is localhost.
.TP
.BI"\-\-tunnel\-port "port
Set the TCP port of the adb tunnel to reach the scrcpy server. This option automatically enables --force-adb-forward.
Set the TCP port of the adb tunnel to reach the scrcpy server. This option automatically enables \fB\-\-force\-adb\-forward\fR.
Default is 0 (not forced): the local port used for establishing the tunnel will be used.
.TP
.B\-v,\-\-version
Print the version of scrcpy.
.TP
.BI"\-V, \-\-verbosity "value
Set the log level ("verbose", "debug", "info", "warn" or "error").
Default is "info" for release builds, "debug" for debug builds.
.TP
.BI"\-\-v4l2-sink "/dev/videoN
Output to v4l2loopback device.
@ -310,14 +481,34 @@ This option is similar to \fB\-\-display\-buffer\fR, but specific to V4L2 sink.
Default is 0 (no buffering).
.TP
.BI"\-V, \-\-verbosity " value
Set the log level ("verbose", "debug", "info", "warn" or "error").
.BI"\-\-video\-codec " name
Select a video codec (h264, h265 or av1).
Default is "info" for release builds, "debug" for debug builds.