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 / client-platform-utilities-and-traits

Client Platform Utilities and Traits

Overview

This area is the native client support layer shared by the rest of app/src: platform wrappers, reusable C primitives, and small trait interfaces for wiring producers to consumers. Most code here is intentionally thin over SDL, FFmpeg, POSIX, or Win32 APIs so higher-level modules can avoid platform branches.

Threading and synchronization are centralized in app/…/thread.h and app/…/thread.c. Threads are SDL threads (sc_thread_create(), sc_thread_join()), mutexes and conditions are SDL mutexes/conditions, and debug builds track the owning thread in sc_mutex.locker so sc_mutex_held()/sc_mutex_assert() can catch misuse. Time uses sc_tick in microseconds from app/…/tick.h; app/…/tick.c reads CLOCK_MONOTONIC on Unix and QueryPerformanceCounter() on Windows. Deadline-based waiting is layered on that in sc_cond_timedwait(), app/…/timeout.c, app/…/acksync.c, and app/…/process.c.

Logging is routed through SDL in app/…/log.h and app/…/log.c. The LOGV/LOGD/LOGI/LOGW/LOGE macros log to the SDL application category, sc_set_log_level() maps the client log enum to SDL priorities, sc_log_configure() installs a stdout/stderr printer, and FFmpeg logs are forwarded via av_log_set_callback() with a [FFmpeg] prefix. Windows-specific error formatting is exposed as sc_log_windows_error() for wrappers such as app/…/net.c.

Process execution is split between the portable facade in app/…/process.h/app/…/process.c and platform implementations in app/…/process.c and app/…/process.c. Callers pass a NULL-terminated argv vector to sc_process_execute_p(), optionally request stdin/stdout/stderr pipes, and later terminate, wait, close, or read pipes through the same facade. Unix uses fork(), execvp(), pipe setup, waitid(), and an internal pipe to report exec failures back to the parent. Windows serializes argv with app/…/command.c, converts it to UTF-16 through app/…/str.c, creates inheritable pipe handles selectively with PROC_THREAD_ATTRIBUTE_HANDLE_LIST, then starts the child with CreateProcessW(). struct sc_process_observer in app/…/process.c creates a helper thread that waits for process termination without owning or closing the process handle.

Network sockets are similarly wrapped by app/…/net.h and app/…/net.c. net_init()/net_cleanup() handle WinSock setup on Windows; net_socket(), net_connect(), net_listen(), net_accept(), net_recv*(), net_send*(), net_set_tcp_nodelay(), and net_parse_ipv4() hide socket type differences. On Windows and macOS, SC_SOCKET_CLOSE_ON_INTERRUPT wraps raw sockets in an allocated struct sc_socket_wrapper because shutdown() does not reliably interrupt blocking accept()/read() there; net_interrupt() closes once with an atomic flag and net_close() still frees the wrapper. app/…/intr.c, app/…/net_intr.c, and app/…/process_intr.c build on this by registering exactly one blocking socket or process with struct sc_intr before a blocking call, so another thread can call sc_intr_interrupt() to close the socket or terminate the process.

File, environment, and terminal helpers hide path encoding and console differences. app/…/file.c builds local paths relative to sc_file_get_executable_path(), while app/…/file.c implements executable discovery through /proc/self/exe, _NSGetExecutablePath(), or _, and app/…/file.c uses GetModuleFileNameW() plus UTF-8/UTF-16 conversion. app/…/env.c duplicates environment values for callers and uses _wgetenv() on Windows. app/…/term.c reads terminal dimensions with ioctl(TIOCGWINSZ) or GetConsoleScreenBufferInfo(), sets terminal/window titles, and emits save/restore title escape sequences only when stdout supports them.

String and memory primitives live in app/…/str.c, app/…/strbuf.c, app/…/memory.c, and app/…/compat.c. sc_strncpy(), sc_str_join(), integer parsers, UTF-8 truncation, line wrapping, column lookup, CR trimming, and hex conversion cover common parsing/formatting. struct sc_strbuf is an owning growable NUL-terminated string buffer; callers free buf.s. Windows string conversion (sc_str_to_wchars()/sc_str_from_wchars()) is compiled only under _WIN32. sc_allocarray() and the fallback reallocarray() guard multiplication overflow with __builtin_mul_overflow(). app/…/compat.h also provides feature-test fallbacks for strdup(), asprintf(), vasprintf(), nrand48(), and jrand48(), plus project-wide printf format compatibility macros and an FFmpeg API-version macro.

Generic collections are macro-based. app/…/vector.h defines SC_VECTOR(type) dynamic arrays with reserve, push, insert, remove, move, shrink, and primitive equality search helpers; items are stored directly in vec.data and vec.size. app/…/vecdeque.h defines SC_VECDEQUE(type), a growable ring buffer with push and pop operations, using sc_allocarray() when wrapped contents must be linearized during growth. app/…/intmap.c performs a linear lookup over static {int32_t key, int32_t value} arrays.

Media and timing helpers include app/…/clock.c, app/…/audiobuf.c, app/…/average.c, app/…/binary.h, and app/…/rand.c. struct sc_clock estimates only the offset between device stream ticks and local system ticks, using a bounded weighted update over SC_CLOCK_RANGE; callers must call sc_clock_update() before sc_clock_to_system_time(). struct sc_audiobuf is a single-producer/single-consumer sample ring buffer with atomic head/tail cursors, explicit sample-size conversion, data reads/writes, and silence insertion. struct sc_average stores a ramp-up rolling average over a configured range. app/…/binary.h contains inline endian readers/writers and fixed-point float conversions for protocol payloads. app/…/rand.c seeds jrand48() state from sc_tick_now() and exposes 32- and 64-bit pseudo-random values.

SDL utility wrappers in app/…/sdl.c normalize window and renderer error handling. They create SDL windows through properties, get/set window size and position using the project struct sc_size/struct sc_point types, and decide which SDL failures are fatal (sc_sdl_get_window_size(), sc_sdl_get_window_position(), sc_sdl_render_present()) versus logged and tolerated (sc_sdl_set_window_size(), sc_sdl_set_window_position(), sc_sdl_render_clear()).

The app/src/trait/** headers are small vtable contracts used to connect independent client components. app/…/packet_source.c and app/…/frame_source.c own fan-out to at most two sinks (SC_PACKET_SOURCE_MAX_SINKS, SC_FRAME_SOURCE_MAX_SINKS): open all sinks in order, close already-opened sinks in reverse on failure, push packets/frames until a sink returns non-SC_SINK_OK, and forward optional session/disable/backpressure callbacks. app/…/packet_sink.h defines the shared struct sc_stream_session metadata passed to packet and frame sinks. Input processor traits in app/…/key_processor.h, app/…/mouse_processor.h, and app/…/gamepad_processor.h expose mandatory and optional callbacks for keyboard/text, mouse/touch, and gamepad events; flags such as sc_key_processor.async_paste, sc_key_processor.hid, and sc_mouse_processor.relative_mode tell upstream input handling how to coordinate acknowledgements, HID-specific behavior, and pointer capture.

Coupling

Risks

  • app/…/timeout.c calls timeout->cbs->on_timeout() after the wait loop regardless of whether sc_timeout_stop() set timeout->stopped. If a caller treats the callback as proof that the deadline expired, then stopping the timeout can trigger timeout handling during normal shutdown.
  • app/…/net.h documents a race in SC_SOCKET_CLOSE_ON_INTERRUPT: on Windows and macOS, net_interrupt() closes the socket to wake blocking calls, and the OS may theoretically reuse the handle before another thread returns from accept() or read(). If code assumes the interrupted handle remains uniquely identifiable until net_close(), it can misattribute activity on a reused descriptor.
  • app/…/str.c implements sc_str_list_contains() with strncmp(list, s, token_len) but does not compare token length with strlen(s). If callers require exact token matching, a list token that is only a prefix of s can be reported as contained.