Client application entry and options
Overview
The native client starts in app/…/main.c. main_scrcpy() prints the SCRCPY_VERSION banner, seeds struct scrcpy_cli_args from scrcpy_options_default, parses the command line with scrcpy_parse_args(), applies the selected log level, optionally saves/sets the terminal title, handles --help and --version, initializes networking and the SDL main-thread runnable gate, then calls either scrcpy(&args.opts) or, when compiled with HAVE_USB and --otg is selected, scrcpy_otg(&args.opts). On Windows, main() first converts the wide command line to UTF-8 argv entries before calling main_scrcpy(), and disables stdio buffering so logs appear immediately. Shutdown in main_scrcpy() always destroys the main-thread gate, cleans up networking, optionally pauses according to --pause-on-exit, and restores the terminal title.
The option state owned by this area is struct scrcpy_options in app/…/options.h, with defaults in app/…/options.c. Defaults encode the client behavior before CLI overrides: display video source, auto audio source, H.264/Opus codecs, SDK-style display control, enabled window/video/audio playback/control/cleanup/power-on, default port range from Meson-generated config, left Alt/Super shortcut modifiers, dark-gray background, terminal title updates, and platform-conditional V4L2/USB fields. options.c also owns orientation composition helpers used by parser validation and record/display transforms.
app/…/cli.c is both the runtime parser and generated --help surface. The options[] table defines short/long option spelling, argument requirements, and help text; sc_getopt_adapter_create_optstring() and sc_getopt_adapter_create_longopts() derive getopt_long() inputs from that table. scrcpy_print_usage() prints options, shortcuts, environment variables (ADB, ANDROID_SERIAL, SCRCPY_ICON_DIR, SCRCPY_SERVER_PATH), and exit statuses. scrcpy_parse_args() calls parse_args_with_getopt(), then resolves --pause-on-exit even after parser failures and defaults it to false except for Windows Explorer-style double-click launches, where it becomes if-error.
After syntactic parsing, parse_args_with_getopt() performs most high-level option normalization and compatibility checks before the rest of the client sees options: it enforces one device selector among --serial, --select-usb, --select-tcpip, and --tcpip=<addr>; derives capture/playback implications for --no-window, --no-video, --no-audio, and --no-playback; disables streams that have no playback/recording/V4L2 sink; rejects “nothing to do”; chooses default audio buffers and audio source; resolves auto/shortcut input modes into SDK, UHID, AOA, or disabled modes; sets default mouse bindings based on SDK vs UHID/AOA; checks camera, new-display/flex-display, OTG, control-only, record-container/codec, hardware-decoder, V4L2, and platform constraints; and implicitly enables --force-adb-forward when tunnel host/port is forced.
The normal client lifecycle is implemented by scrcpy() in app/…/scrcpy.c. It minimally initializes SDL events, initializes the server parameters from struct scrcpy_options, sets SDL hints before starting the server thread, waits for server connection events without blocking Ctrl+C, and then conditionally builds the runtime graph: file pusher, video/audio demuxers, recorder, controller, AOA/UHID/SDK input processors, screen/window, hardware decoder, decoders, video regulators, audio player, V4L2 sink, timeout, initial gamepad discovery, and optional START_APP control message. The main session then runs event_loop(), which converts SDL/custom events into SCRCPY_EXIT_SUCCESS, SCRCPY_EXIT_FAILURE, or SCRCPY_EXIT_DISCONNECTED. Cleanup is explicit and order-sensitive: stop timeout/AOA/controller/file pusher/decoders/regulators/recorder/screen/server, hide the window early on shutdown, join worker threads, destroy decoders before hardware-decoder state, destroy the screen only after demuxers are joined, then destroy the server.
app/…/events.h defines the custom SDL event IDs used as lifecycle glue (SC_EVENT_SERVER_CONNECTED, demuxer/decoder/recorder/controller errors, disconnect, time limit, disconnected icon events, and others). app/…/events.c wraps SDL_PushEvent() for named logging, exposes sc_dequeue_event(), and guards SDL_RunOnMainThread() with a mutex plus a stopped flag so scrcpy() can call sc_main_thread_stop() before tearing down objects that queued runnables might otherwise touch.
app/…/sdl_hints.c centralizes SDL process hints used by normal startup and shared OTG code: requested render driver, app name, mouse focus clickthrough, disabling synthetic touch mouse events, X11 compositor behavior, focus-loss minimization, background joystick events, screensaver behavior, VA-API EGL forcing when compiled with HAVE_VAAPI, and thread-safe Direct3D rendering for D3D11VA. These hints are set in scrcpy.c before starting the server thread to avoid SDL races.
User-visible ancillary entry surfaces are split out. app/…/version.c implements scrcpy_print_version() for --version, reporting compiled/linked SDL and FFmpeg versions plus optional libavdevice/libusb when V4L2/USB are enabled. app/…/icon.c loads scrcpy.png and disconnected.png as SDL surfaces by resolving SCRCPY_ICON_DIR, the installed icon directory, or the portable local path, decoding via FFmpeg, mapping packed AV pixel formats to SDL formats, and storing the owning AVFrame on the SDL surface properties for sc_icon_destroy(). app/…/common.h supplies shared include/config glue and simple macros used throughout these entry files.
app/scrcpy.1 is the installed manual page for the same public option, shortcut, environment-variable, and exit-status surface as app/…/cli.c, but it is hand-maintained rather than generated from options[]. app/meson.build wires this area into the executable: it lists the covered source files in src, sets config values consumed by common.h/config.h (SCRCPY_VERSION, PREFIX, PORTABLE, default port range, HAVE_V4L2, HAVE_USB, hardware-decoder flags), declares SDL/FFmpeg/libusb/libavdevice dependencies, installs scrcpy.1 and icon assets, and includes src/cli.c/src/options.c in the debug test_cli target plus src/options.c in test_orientation.
Path-routable coverage: app/…/main.c owns process entry, early parse, terminal/log/network setup, and final pause/title cleanup; app/…/cli.c/app/…/cli.h own CLI args, help text, parsers, and compatibility normalization; app/…/options.c/app/…/options.h own global option data types/defaults and orientation helpers; app/…/scrcpy.c/app/…/scrcpy.h own normal-mode startup, event-loop exit codes, and ordered shutdown; app/…/events.c/app/…/events.h own custom SDL event IDs and main-thread runnable gating; app/…/sdl_hints.c/app/…/sdl_hints.h own SDL hint policy; app/…/version.c/app/…/version.h own --version; app/…/icon.c/app/…/icon.h own icon path resolution/decoding/destruction; app/…/common.h owns shared config/utility macros; app/scrcpy.1 owns installed manual prose; app/meson.build owns build flags, dependencies, installation, and relevant test wiring.
Coupling
- If an option is added, renamed, or changes semantics in app/…/cli.c, update all three consumers:
struct scrcpy_optionsandscrcpy_options_defaultin app/…/options.h/app/…/options.c, the server/screen/controller parameter mapping in app/…/scrcpy.c, and the hand-written man page inapp/scrcpy.1.scrcpy_print_usage()is generated fromoptions[], butapp/scrcpy.1is not. - If a new option depends on build-time feature flags, wire the same flag through
app/meson.buildconfig (HAVE_USB,HAVE_V4L2,HAVE_VAAPI,HAVE_D3D11VA,HAVE_VIDEOTOOLBOX) and parser guards in app/…/cli.c; otherwise disabled builds may still accept options that later cannot run, or enabled builds may hide available behavior. - If SDL event IDs in app/…/events.h change, check every
sc_push_event()callback and everySDL_WaitEvent()switch in app/…/scrcpy.c; these IDs are the cross-thread contract between server/demuxer/decoder/recorder/controller/timeout callbacks and the lifecycle event loop. - If teardown order changes in app/…/scrcpy.c, preserve the dependency comments there: screen destruction waits for demuxer completion, hardware decoding state outlives the video decoder, and
sc_main_thread_stop()in app/…/events.c must run before objects reachable from queued main-thread callbacks are destroyed. - If icon install paths or names change in
app/meson.build, updateSC_ICON_FILENAME_*in app/…/icon.h,SCRCPY_DEFAULT_ICON_DIRandSCRCPY_ICON_DIRbehavior in app/…/icon.c, and the environment-variable docs in app/…/cli.c andapp/scrcpy.1together. - If terminal-title behavior changes, check both layers: app/…/main.c saves/restores the initial title around the whole process, while app/…/scrcpy.c changes it to
scrcpy - <device name>after server connection.
Risks
- app/…/cli.c and
app/scrcpy.1can drift because help output is generated fromoptions[]but the man page is duplicated manually. Current evidence: app/…/cli.c documents-Gas--gamepad=uhid/--gamepad=aoa, whileapp/scrcpy.1says--keyboard=aoafor-G; the history also contains repeated manpage typo/fix commits such ascd6343ee Fix manpage typosand1a0d3007 Add missing --screen-off-timeout doc in manpage. If only one surface is updated, users and packagers receive conflicting option behavior. - Option compatibility in app/…/cli.c is a dense post-parse matrix. Small changes can silently rewrite user intent before app/…/scrcpy.c sees it, for example disabling video when there is no playback/recording/V4L2 sink, forcing
require_audiowhen video is disabled, selecting audio source from video source, or resolvingSC_*_INPUT_MODE_AUTO. If a new mode bypasses these checks, startup may reach “nothing to do”, use the wrong input backend, or reject valid camera/display/recording combinations. - The cleanup path in app/…/scrcpy.c is fragile because many initialized flags guard paired stop/join/destroy calls across threads and external resources. The file history includes cleanup-order fixes such as
91669808 Destroy objects after join(),f30bdeb1 Add missing call to net_cleanup()in the startup path, and older leak/segfault fixes; changing initialization or adding a component without matching all failure labels can leak threads/sockets or access destroyed screen/decoder state. - app/…/events.c rejects new
SDL_RunOnMainThread()work aftersc_main_thread_stop(), then pumps pending events. If a component queues a main-thread runnable after the stop point in app/…/scrcpy.c, it will fail rather than run against torn-down state; if stop is moved too late, queued callbacks may touch objects already being destroyed.