Introducing a new way to review your PRs.

Read the announcement

genymobile / scrcpy

Display and control your Android device

View on GitHub

13 documents · Updated Nov 16, 2026

docs / server-runtime-connection-and-foundations

Server Runtime, Connection, and Foundations

Overview

The Android server starts in server/…/Server.java, which is launched by app_process rather than as a normal Android app (server/…/AndroidManifest.xml is intentionally empty). Server.main() installs an uncaught-exception logger, drops root to shell UID when needed, prepares a quit-capable main Looper, parses key=value arguments through server/…/Options.java, redirects Java standard streams through server/…/Ln.java, then either prints listing output or enters the mirroring runtime.

Options.parse() treats the first argument as the client version and rejects a client/server version mismatch before applying defaults. It owns the server-side contract for runtime toggles: stream presence (video, audio, control), socket behavior (scid, tunnel_forward), metadata flags (send_device_meta, send_frame_meta, send_dummy_byte, send_stream_meta, and raw_stream), codec/source choices, display/camera/new-display parameters, cleanup behavior, and listing modes. Parsed value objects come from server/src/main/java/com/genymobile/scrcpy/model/**: Size carries encoder-aware size constraining, Orientation encodes rotations/flips and capture-orientation locks, NewDisplay represents optional virtual-display size/DPI, CodecOption parses typed MediaFormat options, and DeviceApp is the app-list value type.

The connection to the desktop is opened by server/…/DesktopConnection.java. It derives the abstract local socket name from scid (scrcpy or scrcpy_%08x) and creates up to three channels in a fixed order: video, then audio, then control. In normal reverse mode it connects to an existing desktop listener; with tunnel_forward=true it creates a LocalServerSocket on the device and accepts the desktop connections. If enabled, a single dummy byte is written on the first accepted forward-tunnel channel so the desktop can detect connection failures. Device metadata, when enabled, is written to the first opened socket as a 64-byte UTF-8-truncated device-name field using StringUtils.getUtf8TruncationIndex() and IO.writeFully().

After connection setup, Server.scrcpy() applies process workarounds (server/…/Workarounds.java), optionally starts persistent cleanup (server/…/CleanUp.java), and builds a list of server/…/AsyncProcessor.java implementations from feature modules. The control module receives connection.getControlChannel() and a shared CleanUp handle; the audio module receives a Streamer wrapping connection.getAudioFd(); the video module receives a Streamer wrapping connection.getVideoFd() and may share its selected SurfaceCapture back to the controller. Each processor is started with a termination callback; Server.Completion quits the main looper when all processors finish or when any processor reports a fatal error. Shutdown reverses startup by interrupting cleanup, stopping and joining processors, shutting down then closing sockets, joining cleanup, and shutting down OpenGL via OpenGLRunner.shutdown().

server/…/Streamer.java is the shared byte-stream abstraction consumed by the video and audio docs. It optionally writes a 4-byte codec id stream header, optional 12-byte frame metadata (pts | config/key-frame flags plus payload size), and optional video session metadata (session flag, width, height, client-resize bit). It also sends disable-stream codes for audio failure/configuration failure. OPUS and FLAC codec-config packets are normalized in-place before writing because Android MediaCodec exposes larger codec-specific-data blocks than the desktop protocol expects.

Runtime cleanup is deliberately out-of-process. CleanUp.start() spawns a thread that records and changes Android settings through server/…/Settings.java, then launches another app_process instance running CleanUp.main() with CLASSPATH=Server.SERVER_PATH. That helper calls setsid(), unlinks the server jar, prepares a main looper for workarounds, waits on stdin until the main server dies, then restores show_touches, stay_on_while_plugged_in, screen_off_timeout, display IME policy, and display power according to the captured arguments plus dynamic display-power messages from CleanUp.setRestoreDisplayPower().

The server runs outside an Android application process, so Workarounds.java and server/…/FakeContext.java fabricate just enough app/process state for framework APIs. Workarounds installs a fake ActivityThread, marks it as a system thread, optionally fills app info and configuration controller fields, creates an Application with FakeContext, and provides an AudioRecord construction path that bypasses vendor constructors while preserving attribution requirements across Android 11, 12, and 14 native setup signatures. FakeContext reports package/op package com.android.shell, returns a shell AttributionSource, exposes a ContentResolver backed by the ActivityManager settings provider, and patches selected framework services' internal mContext so clipboard/activity services use the fake context.

server/…/Device.java is the façade used by control, cleanup, and listing flows for shell-level device actions. It injects key/input events, keeps displays active, toggles display power, rotates displays, reads/writes clipboard text, expands/collapses system panels, lists/finds/starts launchable apps, and sends broadcasts. Most operations are thin orchestration around wrappers in server/src/main/java/com/genymobile/scrcpy/wrappers/**, but Device.setDisplayPower() contains version/vendor policy: it avoids the Android 15 display-power API by default, applies Honor Android 14 workarounds, and switches between SurfaceControl and DisplayControl for physical-display ids.

The wrappers package centralizes hidden Android API access. ServiceManager.java lazily obtains and caches Binder-backed wrappers for window, display, input, power, status bar, clipboard, activity, and camera services. WindowManager.java is consumed by control/video display flows for rotation, display-window listeners, and display IME policy. DisplayManager.java is consumed by video/new-display/listing flows for display ids/info, virtual displays, display-power requests, and display-change listeners; it falls back to parsing dumpsys display when hidden DisplayInfo is unavailable. SurfaceControl.java and DisplayControl.java are consumed by video capture and display-power paths for display tokens, layer/surface transactions, physical displays, and virtual display lifecycle. InputManager.java, ClipboardManager.java, PowerManager.java, StatusBarManager.java, ActivityManager.java, and ContentProvider.java support the control and cleanup docs: input injection and UHID associations, clipboard sync, user activity/screen state, panel shortcuts, app/settings provider access, and broadcasts. The local hidden-API stubs in server/…/IContentProvider.java and AIDL files under server/src/main/aidl/** expose framework-only interfaces (IContentProvider, IDisplayWindowListener, IOnPrimaryClipChangedListener) to the server build.

Reusable utilities under server/src/main/java/com/genymobile/scrcpy/util/** are intentionally small foundations: IO retries Os.write() across EINTR and handles pre-Android-6 ByteBuffer position bugs; LogUtils builds listing output for encoders/displays/cameras/apps; CodecUtils applies typed codec options and filters encoders; AffineMatrix, Binary, BinarySearch, Point, Position, and Size support coordinate transforms, binary protocol decoding, and encoder/display sizing; Threads and HandlerExecutor bridge work onto Android handlers on old APIs; Command executes shell commands; SettingsException wraps settings-provider failures; AndroidVersions.java gives named API constants used across all version-gated code.

Coupling

  • If Options.java changes a socket/metadata option (scid, tunnel_forward, send_*, or raw_stream), verify DesktopConnection.java, Streamer.java, and the desktop protocol together. The channel order in DesktopConnection.open() is positional (video, audio, control), and Streamer conditionally suppresses headers based on the same metadata flags.
  • If a new AsyncProcessor is added in Server.java, ensure it calls its termination listener exactly once and implements stop()/join() consistently. Server.Completion only quits the main looper from processor termination callbacks, while final cleanup assumes every started processor can be stopped and joined after socket shutdown.
  • If cleanup-affecting options are added to Options.java or control code calls new CleanUp methods, update both CleanUp.runCleanUp() and CleanUp.main(). Cleanup state crosses a process boundary as positional string arguments plus single-byte dynamic messages, not as a shared object.
  • If code changes fake-context package identity or attribution in FakeContext.java, verify Workarounds.createAudioRecord(), ContentProvider.java, InputManager.java, ActivityManager.java, and ServiceManager.getCameraManager(). These paths assume shell identity (com.android.shell/SHELL_UID or ROOT_UID for settings provider calls) to keep hidden framework APIs authorized.
  • If display APIs are updated in WindowManager.java, DisplayManager.java, SurfaceControl.java, or DisplayControl.java, verify the video/new-display and control docs. Display info, display rotation, display-power, display listeners, and virtual display creation are split across these wrappers and failures are often logged rather than surfaced as fatal exceptions.
  • If Streamer.java frame or session metadata changes, update both audio and video readers. The same class writes audio headers, video headers, video session resize metadata, frame PTS/config/key-frame flags, and stream-disable sentinel codec ids.
  • If app listing or launching changes in Device.java, keep LogUtils.buildAppListMessage() and ActivityManager.startActivity() in sync. Listing filters launchable apps via PackageManager while starting apps may also force-stop and apply launch-display options.
  • If hidden AIDL stubs under server/src/main/aidl/** change, verify DisplayWindowListener.java, WindowManager.registerDisplayWindowListener(), and clipboard listener usage. These local definitions must match enough of the platform Binder shape for generated stubs to transact safely.

Risks

  • Workarounds.java and FakeContext.java are highly coupled to private Android internals. Git history includes repeated fixes around fake app context and attribution (Create Application instance via instrumentation, Fix permission denial error after Android upgrade) plus a revert/fix sequence for AudioRecord package handling (Revert "Fix AudioRecord package name for Android 16"). If hidden ActivityThread, AudioRecord.native_setup, or AttributionSource signatures drift, audio capture, camera listing, clipboard, or settings access can fail before feature code runs.
  • Device.java, SurfaceControl.java, DisplayControl.java, PowerManager.java, and DisplayManager.java carry display-power workarounds for Android 14/15 and specific vendors. History includes Rollback to old --turn-screen-off for Android 15, Honor Android 14 fixes, and disabling the Android 15 display-power path. If this area is simplified without testing physical multi-display and vendor ROM cases, closing scrcpy can leave displays off/on incorrectly or fail to restore display power.
  • DisplayManager.java and ServiceManager.java are used from multiple threads. History includes Synchronize access to DisplayManager, and DisplayManager.getDisplayInfo() still caches reflective methods while serving both controller and video threads. Removing synchronization or changing lazy initialization can introduce rare races in rotation/display-size updates.
  • DesktopConnection.java and Streamer.java implement a binary protocol without schema negotiation. If stream order, dummy-byte timing, 64-byte device metadata, codec ids, disable-stream codes, or 12-byte frame headers change incompatibly, the desktop may block waiting on the wrong socket or decode payload bytes as metadata.
  • Options.java allows unknown options with a warning but throws for malformed known values. If a client sends a misspelled option, the server silently uses defaults; if it sends a renamed known option in the wrong format, startup aborts before connection. Changes to option names or formats must be coordinated with the desktop launcher.
  • Server.scrcpy() waits in Looper.loop() until an AsyncProcessor reports completion. If video=false, audio=false, and control=false are ever allowed together, the async processor list is empty and no callback will quit the looper, leaving a connected but idle server process.