Compare commits

..

50 Commits

Author SHA1 Message Date
Romain Vimont
d31f858204 Add --audio-encoder option
Similar to --video-encoder, but for audio.
2023-02-19 20:47:20 +01:00
Romain Vimont
0e85424ffb Extract unknown encoder error message
This will allow to reuse the same code for audio encoder selection.
2023-02-19 20:47:14 +01:00
Romain Vimont
44e3fab8de Add support for AAC audio codec
Add option --audio-codec=aac.
2023-02-19 20:47:14 +01:00
Romain Vimont
d953859b77 Add --audio-codec option
Introduce the selection mechanism. Alternative codecs will be added
later.
2023-02-19 20:47:07 +01:00
Romain Vimont
bb90f9377f Add --audio-bit-rate option
Add an option to configure the audio bit-rate.
2023-02-19 20:36:07 +01:00
Romain Vimont
f96e0f4973 Disable MethodLength checkstyle on createOptions()
This method will grow as needed to initialize options.
2023-02-19 20:36:07 +01:00
Romain Vimont
16f4953dea Remove default bit-rate on client side
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
6dd67ef5d4 Record at least video packets on stop
If the recorder is stopped while it has not received any audio packet
yet, make sure the video stream is correctly recorded.
2023-02-19 20:36:07 +01:00
Romain Vimont
0c5d9266a5 Disable audio before Android 11
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/>
2023-02-19 20:36:07 +01:00
Romain Vimont
e285612ee8 Disable audio on initialization error
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
e672dfd6e6 Add record audio support
Make the recorder accept two input sources (video and audio), and mux
them into a single file.
2023-02-19 20:36:07 +01:00
Romain Vimont
753358ec31 Rename video-specific variables in recorder
This paves the way to add audio-specific variables.
2023-02-19 20:36:07 +01:00
Romain Vimont
fe7b51e9a1 Do not merge config audio packets
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
583ee7e950 Add an audio demuxer
Add a demuxer which will read the stream from the audio socket.
2023-02-19 20:36:07 +01:00
Romain Vimont
25e68cd7ba Give a name to demuxer instances
This will be useful in logs.
2023-02-19 20:36:07 +01:00
Romain Vimont
ceb3423b98 Rename demuxer to video_demuxer
There will be another demuxer instance for audio.
2023-02-19 20:36:07 +01:00
Romain Vimont
7f6678d369 Extract OPUS extradata
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
2522c16989 Use a streamer to send the audio stream
Send each encoded audio packet using a streamer.
2023-02-19 20:36:07 +01:00
Romain Vimont
a6b7a857a2 Encode recorded audio on the device
For now, the encoded packets are just logged in the console.
2023-02-19 20:36:07 +01:00
Simon Chan
91717b4eb2 Capture device audio
Create an AudioRecorder to capture the audio source REMOTE_SUBMIX.

For now, the captured packets are just logged in the console.

Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
2023-02-19 20:36:07 +01:00
Simon Chan
e5ce5383e1 Add a new socket for audio stream
When audio is enabled, open a new socket to send the audio stream from
the device to the client.

Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
2023-02-19 20:36:07 +01:00
Simon Chan
b0bff7b761 Add --no-audio option
Audio will be enabled by default (when supported). Add an option to
disable it.

Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
2023-02-19 20:36:07 +01:00
Romain Vimont
fe88d2268e Use FakeContext for Application instance
This will expose the correct package name and UID to the application
context.
2023-02-19 20:36:07 +01:00
Romain Vimont
378fbf2235 Use shell package name for workarounds
For consistency.
2023-02-19 20:36:07 +01:00
Romain Vimont
a09f85819a Use PACKAGE_NAME from FakeContext
Remove duplicated constant.
2023-02-19 20:36:07 +01:00
Romain Vimont
9b66079daf Use AttributionSource from FakeContext
FakeContext already provides an AttributeSource instance.

Co-authored-by: Simon Chan <1330321+yume-chan@users.noreply.github.com>
2023-02-19 20:36:07 +01:00
Simon Chan
a17e2b10a2 Add a fake Android Context
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.

Co-authored-by: Romain Vimont <rom@rom1v.com>
Signed-off-by: Romain Vimont <rom@rom1v.com>
2023-02-19 20:36:07 +01:00
Romain Vimont
ef82a51183 Use Process.ROOT_UID
Replace ServiceManager.USER_ID by existing constant Process.ROOT_UID.
2023-02-19 20:36:07 +01:00
Romain Vimont
345439a0af Improve error message for unknown encoder
The provided encoder name depends on the selected codec. Improve the
error message and the suggestions.
2023-02-19 20:36:07 +01:00
Romain Vimont
c63d4f4066 Rename "codec" variable to "mediaCodec"
This will allow to use "codec" for the Codec type.
2023-02-19 20:36:07 +01:00
Romain Vimont
3d469aa6aa Make streamer independent of codec type
Rename VideoStreamer to Streamer, and extract a Codec interface which
will also support audio codecs.
2023-02-19 20:36:07 +01:00
Romain Vimont
27e8af1e13 Pass all args to ScreenEncoder constructor
There is no good reason to pass some of them in the constructor and some
others as parameters of the streamScreen() method.
2023-02-19 20:36:07 +01:00
Romain Vimont
4b731090dc Move screen encoder initialization
This prepares further refactors.
2023-02-19 20:36:07 +01:00
Romain Vimont
07f482c90b Write streamer header from ScreenEncoder
The screen encoder is responsible to write data to the video streamer.
2023-02-19 20:36:07 +01:00
Romain Vimont
05ca212d5d Use VideoStreamer directly from ScreenEncoder
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
2023-02-19 20:36:07 +01:00
Romain Vimont
9df1a5a63f Simplify error handling on socket creation
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).
2023-02-19 20:36:07 +01:00
Romain Vimont
9e14942a72 Refactor recorder logic
Process the initial config packet (necessary to write the header)
separately.
2023-02-19 20:36:07 +01:00
Romain Vimont
a18ebb778a Move last packet recording
Write the last packet at the end.
2023-02-19 20:36:07 +01:00
Romain Vimont
03c8523a74 Open recording file from the recorder thread
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
fa2ed20d80 Inline packet_sink impl in recorder
Remove useless wrappers.
2023-02-19 20:36:07 +01:00
Romain Vimont
ba5722493d Initialize recorder fields from init()
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, the mutex and condvar would
still be initialized only once.
2023-02-19 20:36:07 +01:00
Romain Vimont
f09eed5aa5 Report recorder errors
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.
2023-02-19 20:36:07 +01:00
Romain Vimont
a1c1edacf9 Move previous packet to a local variable
It is only used from run_recorder().
2023-02-19 20:36:07 +01:00
Romain Vimont
727f2edbfc Move pts_origin to a local variable
It is only used from run_recorder().
2023-02-19 20:36:07 +01:00
Romain Vimont
bda6b8a495 Change PTS origin type from uint64_t to int64_t
It is initialized from AVPacket.pts, which is an int64_t.
2023-02-19 20:36:07 +01:00
Romain Vimont
1fde93b21e Fix --encoder documentation
Mention that it depends on the codec provided by --codec (which is not
necessarily H264 anymore).
2023-02-19 20:36:07 +01:00
Romain Vimont
58d35eca2b Do not print stacktraces when unnecessary
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.
2023-02-19 20:36:06 +01:00
Romain Vimont
ebecbe6bc6 Fix inconsistent quotes
The encoder name started with a simple quote but ended with a
double quote. Use a single quote for both.
2023-02-19 16:18:19 +01:00
Romain Vimont
d5dff239c8 Suggest commands with an explicit '=' 2023-02-19 16:18:19 +01:00
Romain Vimont
5cf86ef7ff Move finally-block to fix deadlock on stop
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
2023-02-19 15:59:05 +01:00
16 changed files with 174 additions and 131 deletions

View File

@@ -31,6 +31,10 @@ Select an audio codec (opus or aac).
Default is opus.
.TP
.BI "\-\-audio\-encoder " name
Use a specific MediaCodec audio encoder (depending on the codec provided by \fB\-\-audio\-codec\fR).
.TP
.BI "\-b, \-\-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).
@@ -94,7 +98,7 @@ Also see \fB\-d\fR (\fB\-\-select\-usb\fR).
.TP
.BI "\-\-encoder " name
Use a specific MediaCodec encoder (must be a H.264 encoder).
Use a specific MediaCodec encoder (depending on the codec provided by \fB\-\-codec\fR).
.TP
.B \-\-force\-adb\-forward

View File

@@ -61,6 +61,7 @@
#define OPT_NO_AUDIO 1041
#define OPT_AUDIO_BIT_RATE 1042
#define OPT_AUDIO_CODEC 1043
#define OPT_AUDIO_ENCODER_NAME 1044
struct sc_option {
char shortopt;
@@ -116,6 +117,13 @@ static const struct sc_option options[] = {
.text = "Select an audio codec (opus or aac).\n"
"Default is opus.",
},
{
.longopt_id = OPT_AUDIO_ENCODER_NAME,
.longopt = "audio-encoder",
.argdesc = "name",
.text = "Use a specific MediaCodec audio encoder (depending on the "
"codec provided by --audio-codec).",
},
{
.shortopt = 'b',
.longopt = "bit-rate",
@@ -191,7 +199,8 @@ static const struct sc_option options[] = {
.longopt_id = OPT_ENCODER_NAME,
.longopt = "encoder",
.argdesc = "name",
.text = "Use a specific MediaCodec encoder (must be a H.264 encoder).",
.text = "Use a specific MediaCodec encoder (depending on the codec "
"provided by --codec).",
},
{
.longopt_id = OPT_FORCE_ADB_FORWARD,
@@ -1634,6 +1643,9 @@ parse_args_with_getopt(struct scrcpy_cli_args *args, int argc, char *argv[],
case OPT_ENCODER_NAME:
opts->encoder_name = optarg;
break;
case OPT_AUDIO_ENCODER_NAME:
opts->audio_encoder_name = optarg;
break;
case OPT_FORCE_ADB_FORWARD:
opts->force_adb_forward = true;
break;

View File

@@ -97,6 +97,7 @@ struct scrcpy_options {
const char *render_driver;
const char *codec_options;
const char *encoder_name;
const char *audio_encoder_name;
#ifdef HAVE_V4L2
const char *v4l2_device;
#endif

View File

@@ -630,7 +630,6 @@ sc_recorder_audio_packet_sink_close(struct sc_packet_sink *sink) {
sc_mutex_lock(&recorder->mutex);
// EOS also stops the recorder
// TODO must stop only once both video and audio stream are complete
recorder->stopped = true;
sc_cond_signal(&recorder->queue_cond);
sc_mutex_unlock(&recorder->mutex);

View File

@@ -368,6 +368,7 @@ scrcpy(struct scrcpy_options *options) {
.stay_awake = options->stay_awake,
.codec_options = options->codec_options,
.encoder_name = options->encoder_name,
.audio_encoder_name = options->audio_encoder_name,
.force_adb_forward = options->force_adb_forward,
.power_off_on_close = options->power_off_on_close,
.clipboard_autosync = options->clipboard_autosync,

View File

@@ -73,6 +73,7 @@ sc_server_params_destroy(struct sc_server_params *params) {
free((char *) params->crop);
free((char *) params->codec_options);
free((char *) params->encoder_name);
free((char *) params->audio_encoder_name);
free((char *) params->tcpip_dst);
}
@@ -97,6 +98,7 @@ sc_server_params_copy(struct sc_server_params *dst,
COPY(crop);
COPY(codec_options);
COPY(encoder_name);
COPY(audio_encoder_name);
COPY(tcpip_dst);
#undef COPY
@@ -270,6 +272,9 @@ execute_server(struct sc_server *server,
if (params->encoder_name) {
ADD_PARAM("encoder_name=%s", params->encoder_name);
}
if (params->audio_encoder_name) {
ADD_PARAM("audio_encoder_name=%s", params->audio_encoder_name);
}
if (params->power_off_on_close) {
ADD_PARAM("power_off_on_close=true");
}

View File

@@ -30,6 +30,7 @@ struct sc_server_params {
const char *crop;
const char *codec_options;
const char *encoder_name;
const char *audio_encoder_name;
struct sc_port_range port_range;
uint32_t tunnel_host;
uint16_t tunnel_port;

View File

@@ -45,6 +45,7 @@ public final class AudioEncoder {
private final Streamer streamer;
private final int bitRate;
private final String encoderName;
private AudioRecord recorder;
private MediaCodec mediaCodec;
@@ -62,9 +63,10 @@ public final class AudioEncoder {
private boolean ended;
public AudioEncoder(Streamer streamer, int bitRate) {
public AudioEncoder(Streamer streamer, int bitRate, String encoderName) {
this.streamer = streamer;
this.bitRate = bitRate;
this.encoderName = encoderName;
}
private static AudioFormat createAudioFormat() {
@@ -200,17 +202,23 @@ public final class AudioEncoder {
@TargetApi(Build.VERSION_CODES.M)
public void encode() throws IOException {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
Ln.w("Audio disabled: it is not supported before Android 11");
streamer.writeDisableStream();
return;
}
try {
try {
String mimeType = streamer.getCodec().getMimeType();
Codec codec = streamer.getCodec();
mediaCodec = MediaCodec.createEncoderByType(mimeType); // may throw IOException
mediaCodec = createMediaCodec(codec, encoderName);
recorder = createAudioRecord();
mediaCodecThread = new HandlerThread("AudioEncoder");
mediaCodecThread.start();
MediaFormat format = createFormat(mimeType, bitRate);
MediaFormat format = createFormat(codec.getMimeType(), bitRate);
mediaCodec.setCallback(new EncoderCallback(), new Handler(mediaCodecThread.getLooper()));
mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
@@ -249,6 +257,8 @@ public final class AudioEncoder {
mediaCodec.start();
inputThread.start();
outputThread.start();
} catch (ConfigurationException e) {
// Do not print stack trace, a user-friendly error-message has already been logged
} catch (Throwable e) {
if (mediaCodec != null) {
mediaCodec.release();
@@ -266,6 +276,21 @@ public final class AudioEncoder {
}
}
private static MediaCodec createMediaCodec(Codec codec, String encoderName) throws IOException, ConfigurationException {
if (encoderName != null) {
Ln.d("Creating audio encoder by name: '" + encoderName + "'");
try {
return MediaCodec.createByCodecName(encoderName);
} catch (IllegalArgumentException e) {
Ln.e(CodecUtils.buildUnknownEncoderMessage(codec, encoderName));
throw new ConfigurationException("Unknown encoder: " + encoderName);
}
}
MediaCodec mediaCodec = MediaCodec.createEncoderByType(codec.getMimeType());
Ln.d("Using audio encoder: '" + mediaCodec.getName() + "'");
return mediaCodec;
}
private void cleanUp() {
mediaCodecThread.getLooper().quit();
inputThread.interrupt();

View File

@@ -0,0 +1,40 @@
package com.genymobile.scrcpy;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class CodecUtils {
private CodecUtils() {
// not instantiable
}
public static String buildUnknownEncoderMessage(Codec codec, String encoderName) {
StringBuilder msg = new StringBuilder("Encoder '").append(encoderName).append("' for ").append(codec.getName()).append(" not found");
MediaCodecInfo[] encoders = listEncoders(codec.getMimeType());
if (encoders != null && encoders.length > 0) {
msg.append("\nTry to use one of the available encoders:");
String codecOption = codec.getType() == Codec.Type.VIDEO ? "codec" : "audio-codec";
for (MediaCodecInfo encoder : encoders) {
msg.append("\n scrcpy --").append(codecOption).append("=").append(codec.getName());
msg.append(" --encoder='").append(encoder.getName()).append("'");
}
}
return msg.toString();
}
private static MediaCodecInfo[] listEncoders(String mimeType) {
List<MediaCodecInfo> result = new ArrayList<>();
MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
for (MediaCodecInfo codecInfo : list.getCodecInfos()) {
if (codecInfo.isEncoder() && Arrays.asList(codecInfo.getSupportedTypes()).contains(mimeType)) {
result.add(codecInfo);
}
}
return result.toArray(new MediaCodecInfo[result.size()]);
}
}

View File

@@ -0,0 +1,7 @@
package com.genymobile.scrcpy;
public class ConfigurationException extends Exception {
public ConfigurationException(String message) {
super(message);
}
}

View File

@@ -61,12 +61,12 @@ public final class Device {
private final boolean supportsInputEvents;
public Device(Options options) {
public Device(Options options) throws ConfigurationException {
displayId = options.getDisplayId();
DisplayInfo displayInfo = ServiceManager.getDisplayManager().getDisplayInfo(displayId);
if (displayInfo == null) {
int[] displayIds = ServiceManager.getDisplayManager().getDisplayIds();
throw new InvalidDisplayIdException(displayId, displayIds);
Ln.e(buildUnknownDisplayIdMessage(displayId));
throw new ConfigurationException("Unknown display id: " + displayId);
}
int displayInfoFlags = displayInfo.getFlags();
@@ -130,6 +130,18 @@ public final class Device {
}
}
private static String buildUnknownDisplayIdMessage(int displayId) {
StringBuilder msg = new StringBuilder("Display ").append(displayId).append(" not found");
int[] displayIds = ServiceManager.getDisplayManager().getDisplayIds();
if (displayIds != null && displayIds.length > 0) {
msg.append("\nTry to use one of the available display ids:");
for (int id : displayIds) {
msg.append("\n scrcpy --display=").append(id);
}
}
return msg.toString();
}
public synchronized void setMaxSize(int newMaxSize) {
maxSize = newMaxSize;
screenInfo = ScreenInfo.computeScreenInfo(screenInfo.getReverseVideoRotation(), deviceSize, crop, newMaxSize, lockVideoOrientation);

View File

@@ -1,21 +0,0 @@
package com.genymobile.scrcpy;
public class InvalidDisplayIdException extends RuntimeException {
private final int displayId;
private final int[] availableDisplayIds;
public InvalidDisplayIdException(int displayId, int[] availableDisplayIds) {
super("There is no display having id " + displayId);
this.displayId = displayId;
this.availableDisplayIds = availableDisplayIds;
}
public int getDisplayId() {
return displayId;
}
public int[] getAvailableDisplayIds() {
return availableDisplayIds;
}
}

View File

@@ -1,23 +0,0 @@
package com.genymobile.scrcpy;
import android.media.MediaCodecInfo;
public class InvalidEncoderException extends RuntimeException {
private final String name;
private final MediaCodecInfo[] availableEncoders;
public InvalidEncoderException(String name, MediaCodecInfo[] availableEncoders) {
super("There is no encoder having name '" + name + '"');
this.name = name;
this.availableEncoders = availableEncoders;
}
public String getName() {
return name;
}
public MediaCodecInfo[] getAvailableEncoders() {
return availableEncoders;
}
}

View File

@@ -24,6 +24,7 @@ public class Options {
private boolean stayAwake;
private List<CodecOption> codecOptions;
private String encoderName;
private String audioEncoderName;
private boolean powerOffScreenOnClose;
private boolean clipboardAutosync = true;
private boolean downsizeOnError = true;
@@ -180,6 +181,14 @@ public class Options {
this.encoderName = encoderName;
}
public String getAudioEncoderName() {
return audioEncoderName;
}
public void setAudioEncoderName(String audioEncoderName) {
this.audioEncoderName = audioEncoderName;
}
public void setPowerOffScreenOnClose(boolean powerOffScreenOnClose) {
this.powerOffScreenOnClose = powerOffScreenOnClose;
}

View File

@@ -5,7 +5,6 @@ import com.genymobile.scrcpy.wrappers.SurfaceControl;
import android.graphics.Rect;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.os.Build;
import android.os.IBinder;
@@ -14,8 +13,6 @@ import android.view.Surface;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -62,10 +59,10 @@ public class ScreenEncoder implements Device.RotationListener {
return rotationChanged.getAndSet(false);
}
public void streamScreen() throws IOException {
String videoMimeType = streamer.getCodec().getMimeType();
MediaCodec codec = createCodec(videoMimeType, encoderName);
MediaFormat format = createFormat(videoMimeType, bitRate, maxFps, codecOptions);
public void streamScreen() throws IOException, ConfigurationException {
Codec codec = streamer.getCodec();
MediaCodec mediaCodec = createMediaCodec(codec, encoderName);
MediaFormat format = createFormat(codec.getMimeType(), bitRate, maxFps, codecOptions);
IBinder display = createDisplay();
device.setRotationListener(this);
@@ -84,8 +81,8 @@ public class ScreenEncoder implements Device.RotationListener {
Surface surface = null;
try {
codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
surface = codec.createInputSurface();
mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
surface = mediaCodec.createInputSurface();
// does not include the locked video orientation
Rect unlockedVideoRect = screenInfo.getUnlockedVideoSize().toRect();
@@ -93,11 +90,11 @@ public class ScreenEncoder implements Device.RotationListener {
int layerStack = device.getLayerStack();
setDisplaySurface(display, surface, videoRotation, contentRect, unlockedVideoRect, layerStack);
codec.start();
mediaCodec.start();
alive = encode(codec, streamer);
alive = encode(mediaCodec, streamer);
// do not call stop() on exception, it would trigger an IllegalStateException
codec.stop();
mediaCodec.stop();
} catch (IllegalStateException | IllegalArgumentException e) {
Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage());
if (!prepareRetry(device, screenInfo)) {
@@ -106,14 +103,14 @@ public class ScreenEncoder implements Device.RotationListener {
Ln.i("Retrying...");
alive = true;
} finally {
codec.reset();
mediaCodec.reset();
if (surface != null) {
surface.release();
}
}
} while (alive);
} finally {
codec.release();
mediaCodec.release();
device.setRotationListener(null);
SurfaceControl.destroyDisplay(display);
}
@@ -199,30 +196,19 @@ public class ScreenEncoder implements Device.RotationListener {
return !eof;
}
private static MediaCodecInfo[] listEncoders(String videoMimeType) {
List<MediaCodecInfo> result = new ArrayList<>();
MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
for (MediaCodecInfo codecInfo : list.getCodecInfos()) {
if (codecInfo.isEncoder() && Arrays.asList(codecInfo.getSupportedTypes()).contains(videoMimeType)) {
result.add(codecInfo);
}
}
return result.toArray(new MediaCodecInfo[result.size()]);
}
private static MediaCodec createCodec(String videoMimeType, String encoderName) throws IOException {
private static MediaCodec createMediaCodec(Codec codec, String encoderName) throws IOException, ConfigurationException {
if (encoderName != null) {
Ln.d("Creating encoder by name: '" + encoderName + "'");
try {
return MediaCodec.createByCodecName(encoderName);
} catch (IllegalArgumentException e) {
MediaCodecInfo[] encoders = listEncoders(videoMimeType);
throw new InvalidEncoderException(encoderName, encoders);
Ln.e(CodecUtils.buildUnknownEncoderMessage(codec, encoderName));
throw new ConfigurationException("Unknown encoder: " + encoderName);
}
}
MediaCodec codec = MediaCodec.createEncoderByType(videoMimeType);
Ln.d("Using encoder: '" + codec.getName() + "'");
return codec;
MediaCodec mediaCodec = MediaCodec.createEncoderByType(codec.getMimeType());
Ln.d("Using encoder: '" + mediaCodec.getName() + "'");
return mediaCodec;
}
private static void setCodecOption(MediaFormat format, CodecOption codecOption) {

View File

@@ -1,7 +1,6 @@
package com.genymobile.scrcpy;
import android.graphics.Rect;
import android.media.MediaCodecInfo;
import android.os.BatteryManager;
import android.os.Build;
@@ -59,7 +58,7 @@ public final class Server {
}
}
private static void scrcpy(Options options) throws IOException {
private static void scrcpy(Options options) throws IOException, ConfigurationException {
Ln.i("Device: " + Build.MANUFACTURER + " " + Build.MODEL + " (Android " + Build.VERSION.RELEASE + ")");
final Device device = new Device(options);
List<CodecOption> codecOptions = options.getCodecOptions();
@@ -93,6 +92,9 @@ public final class Server {
Workarounds.fillAppInfo();
}
Controller controller = null;
AudioEncoder audioEncoder = null;
try (DesktopConnection connection = DesktopConnection.open(scid, tunnelForward, audio, control, sendDummyByte)) {
VideoCodec codec = options.getCodec();
if (options.getSendDeviceMeta()) {
@@ -100,7 +102,6 @@ public final class Server {
connection.sendDeviceMeta(Device.getDeviceName(), videoSize.getWidth(), videoSize.getHeight());
}
Controller controller = null;
if (control) {
controller = new Controller(device, connection, options.getClipboardAutosync(), options.getPowerOn());
controller.start();
@@ -109,11 +110,10 @@ public final class Server {
device.setClipboardListener(text -> controllerRef.getSender().pushClipboardText(text));
}
AudioEncoder audioEncoder = null;
if (audio) {
Streamer audioStreamer = new Streamer(connection.getAudioFd(), options.getAudioCodec(), options.getSendCodecId(),
options.getSendFrameMeta());
audioEncoder = new AudioEncoder(audioStreamer, options.getAudioBitRate());
audioEncoder = new AudioEncoder(audioStreamer, options.getAudioBitRate(), options.getAudioEncoderName());
audioEncoder.start();
}
@@ -128,27 +128,27 @@ public final class Server {
if (!IO.isBrokenPipe(e)) {
Ln.e("Video encoding error", e);
}
} finally {
Ln.d("Screen streaming stopped");
initThread.interrupt();
}
} finally {
Ln.d("Screen streaming stopped");
initThread.interrupt();
if (audioEncoder != null) {
audioEncoder.stop();
}
if (controller != null) {
controller.stop();
}
try {
initThread.join();
if (audioEncoder != null) {
audioEncoder.stop();
audioEncoder.join();
}
if (controller != null) {
controller.stop();
}
try {
initThread.join();
if (audioEncoder != null) {
audioEncoder.join();
}
if (controller != null) {
controller.join();
}
} catch (InterruptedException e) {
// ignore
controller.join();
}
} catch (InterruptedException e) {
// ignore
}
}
}
@@ -264,6 +264,10 @@ public final class Server {
options.setEncoderName(value);
}
break;
case "audio_encoder_name":
if (!value.isEmpty()) {
options.setAudioEncoderName(value);
}
case "power_off_on_close":
boolean powerOffScreenOnClose = Boolean.parseBoolean(value);
options.setPowerOffScreenOnClose(powerOffScreenOnClose);
@@ -334,38 +338,19 @@ public final class Server {
return new Rect(x, y, x + width, y + height);
}
private static void suggestFix(Throwable e) {
if (e instanceof InvalidDisplayIdException) {
InvalidDisplayIdException idie = (InvalidDisplayIdException) e;
int[] displayIds = idie.getAvailableDisplayIds();
if (displayIds != null && displayIds.length > 0) {
Ln.e("Try to use one of the available display ids:");
for (int id : displayIds) {
Ln.e(" scrcpy --display " + id);
}
}
} else if (e instanceof InvalidEncoderException) {
InvalidEncoderException iee = (InvalidEncoderException) e;
MediaCodecInfo[] encoders = iee.getAvailableEncoders();
if (encoders != null && encoders.length > 0) {
Ln.e("Try to use one of the available encoders:");
for (MediaCodecInfo encoder : encoders) {
Ln.e(" scrcpy --encoder '" + encoder.getName() + "'");
}
}
}
}
public static void main(String... args) throws Exception {
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
Ln.e("Exception on thread " + t, e);
suggestFix(e);
});
Options options = createOptions(args);
Ln.initLogLevel(options.getLogLevel());
scrcpy(options);
try {
scrcpy(options);
} catch (ConfigurationException e) {
// Do not print stack trace, a user-friendly error-message has already been logged
}
}
}