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
- If a blocking socket or process call is made interruptible, pair the registration and unregistration exactly as in app/…/net_intr.c and app/…/process_intr.c; app/…/intr.c asserts that only one of
intr->socketorintr->processis active, andsc_intr_destroy()asserts both are cleared. - If socket lifetime behavior changes in app/…/net.c, verify all callers still call
net_close()even afternet_interrupt(): on Windows/macOSnet_interrupt()may close the raw socket, butnet_close()is still responsible for freeing thestruct sc_socket_wrapperallocated bywrap(). - If process argv quoting changes, update app/…/command.c and app/…/process.c together; Windows process creation receives one UTF-16 command line, not an argv array, so
sc_command_serialize_windows()is the contract that preserves argument boundaries forCreateProcessW(). - If
sc_tickunits or conversion macros change in app/…/tick.h, audit app/…/thread.c, app/…/timeout.c, app/…/acksync.c, app/…/process.c, app/…/clock.c, and app/…/rand.c; their deadlines, smoothing offsets, and random seed all assume microsecond ticks. - If
struct sc_stream_sessionchanges in app/…/packet_sink.h, update both packet and frame paths: app/…/packet_source.c passes sessions to packet sinks, while app/…/frame_source.c passes the same session shape to frame sinks through app/…/frame_sink.h. - If a source needs more than two consumers, change the source limit and fan-out logic in both app/…/packet_source.h/.c or app/…/frame_source.h/.c;
sc_*_source_add_sink()currently asserts before overflowing the fixedsinks[]array. - If app/…/strbuf.c append semantics are relaxed to allow empty strings, check callers such as app/…/str.c and app/…/command.c;
sc_strbuf_append()currently asserts*s, so append-empty must use no call or a different helper. - If Windows UTF-8/UTF-16 conversion in app/…/str.c changes, verify app/…/file.c, app/…/env.c, app/…/term.c, and app/…/process.c, which rely on those conversions before calling wide Win32 APIs.
Risks
- app/…/timeout.c calls
timeout->cbs->on_timeout()after the wait loop regardless of whethersc_timeout_stop()settimeout->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 fromaccept()orread(). If code assumes the interrupted handle remains uniquely identifiable untilnet_close(), it can misattribute activity on a reused descriptor. - app/…/str.c implements
sc_str_list_contains()withstrncmp(list, s, token_len)but does not compare token length withstrlen(s). If callers require exact token matching, a list token that is only a prefix ofscan be reported as contained.