ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Development & Debugging

🔧 Build system, testing infrastructure, and debugging utilities More...

Topics

 Build System
 Configure, build, test, package, and document ascii-chat.
 Debugging
 🐛 Tools to help you figure out what's going on with the code
 Defer Statements
 Block-scoped cleanup statements for C, Objective-C, and C++.
 Errors
 ❌ When things go wrong and ending the program unsuccessfully
 Lock Debugging and Deadlock Detection
 🔒 Lock debugging infrastructure with backtrace capture and interactive monitoring
 Panic Instrumentation
 🚨 Per-statement logging for crash debugging in C programs
 Query Tool
 HTTP-based runtime variable inspection using external LLDB.

Detailed Description

🔧 Build system, testing infrastructure, and debugging utilities

Build configuration, test framework, debugging tools, and lock debugging.

Continuous integration

Migrated from docs/ci.md into the rendered Doxygen topic set.

Continuous integration

Pull requests and pushes run Linux native validation automatically. Build, Test Suite, Code Analysis, Security and Markdown Linting cancel superseded runs for the same workflow and PR or branch. Closing a PR cancels its remaining validation runs; deployment and publication workflows are excluded from that cleanup. Container publication finishes its active run while keeping only the latest pending run.

Native compilation waits for workflow validation, patch whitespace and changed C/C++ formatting checks. Browser tests wait for web type/lint and unit checks. Web and container workflows use input-specific path filters; shared native headers, dependencies and build configuration still trigger native checks.

Full platform validation

In GitHub Actions, select Build or Test Suite, choose Run workflow, select the branch to test and enable Run the full native platform matrix. The default is off. These workflows can also be dispatched with the CLI:

gh workflow run build.yml --ref YOUR_BRANCH -f full_matrix=true
gh workflow run test.yml --ref YOUR_BRANCH -f full_matrix=true

Build includes all six existing Linux/macOS/Windows architecture combinations when requested. Test Suite restores its existing macOS and Windows jobs where supported. Automatic Test Suite runs keep Linux Debug/Release, integration, performance, memory and functional checks. Complete cross-platform coverage aggregation/publication runs only with the full Test Suite matrix, because its validator requires all seven reports; automatic runs retain individual reports.

Release and website deployment workflows retain their separate publication policies. Manual full validation is a user decision; agents do not need a new instruction or special PR label.

CMake workflows

Migrated from docs/cmake-workflows.md into the rendered Doxygen topic set.

CMake workflows

Use Clang and Ninja on every platform. default keeps the usual build/ directory, and release keeps build_release/ for existing packaging scripts. Other build variants get distinct directories under build/<preset>/, except presets with explicit CI or tooling paths. The directory convention is the same on Windows, Linux and macOS.

cmake --workflow --preset check-default
cmake --workflow --preset check-shared
cmake --workflow --preset check-static

These workflows configure, build the executable and run its --version smoke test. shared explicitly selects system libc and shared dependencies. static uses the release platform policy, including musl on supported Linux hosts. Static and shared library targets remain available independently of the executable's dependency policy.

On Catch2-supported systems, cmake --workflow --preset tests builds the test target and runs the complete suite. The unit, integration and performance test presets use the tests-enabled configuration. Windows does not support Catch2; use the executable smoke workflows there. On Intel macOS, run Catch2 tests through Docker as described in AGENTS.md.

Dependency source downloads can be shared. New configurations keep legacy dependency build/install outputs inside their own binary directories. Explicit cache-directory overrides remain supported. Once configured, a build tree rejects changes to compiler, target ABI, CRT or static/shared dependency policy; select another preset or use cmake --fresh to change those settings.

Musl toolchain

USE_MUSL=ON selects cmake/toolchains/Musl.cmake before project(). It selects Clang's target triple, musl headers and CRT startup files and keeps host package searches out of the target build. Programs such as Perl and Make still run on the host. ASCIICHAT_MUSL_SYSROOT can select a complete target SDK; otherwise the toolchain discovers the distribution's packaged musl paths.

The platform module stages the matching Alpine C++ runtime and non-CMake libraries. Source dependencies use the same compiler/header settings through MuslFlags.cmake. Project C++ sources use those runtime headers as well. Use a fresh configuration when adopting the toolchain in a pre-existing musl build tree. A separate shared/glibc preset produces libraries for glibc hosts.

Installed SDK

Build static-lib and/or shared-lib, then install the Development component. Both find_package(asciichat CONFIG REQUIRED) and find_package(ascii-chat CONFIG REQUIRED) are supported. The package version tracks the library ABI (lib/v*), independently of the executable's version. For the current 0.x ABI, version compatibility is restricted to the same minor.

Use COMPONENTS shared or COMPONENTS static to require a particular variant. The targets are asciichat::shared and asciichat::static, with the existing ascii-chat::* spellings retained. asciichat::asciichat selects an available shared library first. A shared-only consumer does not resolve static link requirements. Archives built with IPO propagate Clang ThinLTO linker options (including LLD on Linux). Static consumers need pkg-config and the required development packages; missing dependencies fail during configuration. Config files and selected source-built support libraries relocate with the installed prefix.

Windows consumers can match the SDK's CRT with the target property MSVC_RUNTIME_LIBRARY=${asciichat_MSVC_RUNTIME_LIBRARY}. The installed-SDK smoke project demonstrates this without changing the consumer's global flags.

Formatting

cmake --Build System Build System --target format formats all owned C, C++, Objective-C, headers and C-family templates, including public headers and every test type. format-check checks the same inventory; clang-format and clang-format-check are aliases. Git checkouts include tracked and newly created nonignored source files while excluding submodules and generated outputs. Source archives use the authored source directories instead. The inventory is collected when the target runs and passed through a response file, so Windows command-line limits and new test files are handled consistently. Run vp format from web/ for frontend code.

Dependencies

CMake can use installed packages or the repository's source dependency cache. The build selects only the features enabled for the target platform; a docs build does not configure the native dependency graph.

Runtime libraries

The main application uses FFmpeg for media input/decoding/encoding, PortAudio for native audio, libwebsockets for WebSocket transport, ngtcp2/nghttp3 and TLS support for QUIC/WebTransport where enabled, SQLite for discovery state, and platform libraries for terminal, threading, and device access.

Other project dependencies include libsodium/BearSSL or the selected crypto backend, zstd compression, utf8proc text handling, and the SIMD/rendering support selected by the platform build.

Build sources

ASCIICHAT_BUILD_DEPS_FROM_SOURCE controls source-built dependency selection when packages are unavailable or a reproducible cache is desired. Submodules must be initialized for native builds that use vendored dependencies. The docs-only CMake project needs only Doxygen and the documentation theme.

Native dependency source and build trees live under .deps-cache/<BuildType>/, including FetchContent's -src, -Build System, and temporary directories. FetchContent creates both source and binary trees; its base directory is therefore isolated by build configuration. An older ASCIICHAT_DEPS_CACHE_DIR equal to the cache root is normalized to this layout on reconfiguration. Explicit separate cache directories remain valid. Docker uses .deps-cache/docker/<DOCKER_OS>/<BuildType>/, with DOCKER_OS distinguishing architectures such as amd64 and arm64. A container without that variable uses .deps-cache/docker/<BuildType>/ with a configure warning. WSL uses .deps-cache/wsl/<WSL_DISTRO_NAME>/<BuildType>/; Arch and Ubuntu retain separate caches. The distro name is sanitized for use in a path, with the distribution ID from /etc/os-release as a fallback. The test Compose configuration and PowerShell Docker driver bind the host's .deps-cache/docker to /app/.deps-cache/docker, preserving these same architecture partitions across runs. Native Windows, Docker, WSL, and musl dependency outputs must not be combined. Musl adds musl/ beneath the selected configuration cache. Shared tools and vcpkg installations remain directly under the selected platform/distro cache root. Dependency patch markers live under patches/<dependency>/ in that same root, preserving platform isolation. Existing generated build trees must be reconfigured before removing their old cache directories; CMake and Ninja files contain absolute paths.

Platform differences

Windows uses the repository's Clang/Ninja path and native console/audio backends. Linux and macOS use their platform terminal/device layers. iOS builds use the reduced static library path and omit desktop-only subsystems; see CMake Build System for the current Apple workflow.

Troubleshooting

Inspect the CMake configure summary before changing flags. Clear only the affected dependency cache after a failed source build, and never mix a stale submodule directory with a different checkout. For documentation, configure cmake -S docs instead of running the full native configure.

See also
topic_build
topic_testing

Dependency builds

Migrated from docs/dependency-builds.md into the rendered Doxygen topic set.

Dependency builds

Native builds normally use installed packages where supported. Configure with -DASCIICHAT_BUILD_DEPS_FROM_SOURCE=ON to exercise the source implementations of the converted dependencies. This still requires the platform SDK and packages for dependencies that do not have an upstream CMake build, including OpenSSL.

The source implementations use upstream CMake targets for PCRE2, Opus, zstd, zlib, PortAudio, FreeType, Expat, Abseil, miniupnpc, libdatachannel and its networking dependencies, libwebsockets, WebRTC AEC3, x265, mimalloc, and utf8proc. mdns uses its upstream interface target. FFTW, libuv and yyjson already use upstream CMake builds. libvterm has a small local target because upstream supplies a Makefile; its generated encoding tables are tracked build outputs.

FetchContent downloads pinned sources during configuration. The upstream targets compile when cmake --Build System runs, so Ninja handles their ordering, incremental rebuilds, compiler settings, include paths and transitive links. Upstream options are scoped to each dependency. Sources can be cached between configurations, while each build directory keeps its own generated files and objects.

Debug and Dev builds default to shared native dependencies; Release-style builds default to static dependencies. BUILD_SHARED_LIBS=ON explicitly selects shared dependencies and BUILD_SHARED_LIBS=OFF explicitly selects static dependencies. WASM, iOS and musl retain their static dependency policy. AEC3's upstream components remain static and can be linked into either the shared ascii-chat library or an executable. CMake records the circular dependency between its factory and implementation, so consumers do not need whole-archive flags or hand-written archive lists.

FFmpeg and Fontconfig consume installed codec/font dependencies through pkg-config. Small staging targets install x265, FreeType and Expat into the build tree before those external builds run. This keeps their configure scripts out of the top-level configure step without replacing their supported upstream build systems. libsodium, OpenSSL, ALSA, x264, BearSSL and libexecinfo likewise retain their upstream build systems where source builds are required.

On Windows, native builds use Clang, Ninja and the Visual Studio SDK environment. CMake selects the MSVC-compatible C runtime for both application code and third-party DLLs. No SHELL environment override is required. WASM's remaining Autotools dependency, libsodium, uses Bash and Make from one MSYS2 installation; ASCIICHAT_MSYS2_ROOT can identify it when automatic discovery is insufficient. Windows shared builds select Abseil's upstream single DLL option, including when Clang uses its GNU-style command line with the MSVC ABI.

Testing source targets

The dependency smoke executable exercises compression round trips, an Opus encoder, PCRE2 compilation, FreeType, PortAudio metadata, UPnP, XML parsing, terminal allocation, Unicode widths, TLS/WebRTC library initialization, an AEC3 factory and mimalloc allocation. It does not open cameras, audio devices or network connections.

cmake -S tests/cmake/dependencies -B build/dependency-static -G Ninja \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
-DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF
cmake --build build/dependency-static
ctest --test-dir build/dependency-static --output-on-failure
cmake -S tests/cmake/dependencies -B build/dependency-shared -G Ninja \
-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
-DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON
cmake --build build/dependency-shared
ctest --test-dir build/dependency-shared --output-on-failure

Set OPENSSL_ROOT_DIR when OpenSSL is outside the normal search paths. Windows must also be able to load its OpenSSL DLLs when running the smoke executable. The WASM build has a separate wasm-dependencies target and CTest entry.

MCP rendering server

Migrated from docs/mcp.md into the rendered Doxygen topic set.

MCP rendering server

ascii-chat mcp-server exposes four rendering tools over newline-delimited JSON-RPC on stdio. It runs through the ordinary application initialization, options, logging, error-stack and diagnostic workers. Both transports automatically skip startup update checks. Protocol stdout is reserved before initialization; incidental terminal diagnostics go to stderr.

ascii-chat mcp-server --transport http serves all five tools at /mcp using MCP Streamable HTTP and libwebsockets. The default listener is 127.0.0.1:27228, following the native TCP and WebSocket defaults (27224–27227). Override it with --port, ASCII_CHAT_PORT, --address, --address6, or the existing zero-to-two positional IPv4/IPv6 bind addresses. Examples:

ascii-chat mcp-server --transport http --port 28028 --address 127.0.0.1
ascii-chat mcp-server --transport http 0.0.0.0 ::1 --port 27228
ascii-chat --log-level debug --grep 'MCP|render' mcp-server --transport http --status-screen

The shared --tls-cert, --tls-key, and --tls-key-password options configure HTTPS for this HTTP listener too. --port-forwarding maps the HTTP port with the existing UPnP implementation. Concurrent render jobs default to the number of CPUs available to the process; --max-clients can set a lower limit. HTTP status uses the shared terminal controller and log viewer, including error popups and debug controls. Debug builds retain --sync-state, --backtrace, and memory diagnostics. Stdio does not consume terminal keys: stdin is the protocol stream.

For mcp.ascii-chat.com, terminate HTTPS and enforce rate/body/concurrency limits at a reverse proxy. The configured browser Origin defaults to https://mcp.ascii-chat.com; change it with --http-origin. Requests without Origin are accepted for native MCP clients. The implementation uses stateless JSON responses; POST to /mcp handles requests and notifications, while GET/DELETE on /mcp return 405. In restricted HTTP mode, GET /downloads/<name> serves temporary exports. It supports MCP versions 2025-03-26, 2025-06-18, and 2025-11-25. Clients send Accept including application/json and text/event-stream.

Tools

  • render_file: exactly one of path or data_base64, optional mime_type. A source may be omitted when options select synthetic test video/audio.
  • render_url: url for media supported by the CLI FFmpeg/yt-dlp resolver.
  • device_list: no arguments. Returns video_devices and audio_devices (microphones), each with index, name, and is_default, plus default_video_device and default_audio_device (null when absent). Webcam default is index 0; microphone default comes from the OS. Enumeration failures appear in errors, preserving devices discovered in the other category. Hidden with --server.
  • render_webcam: optional video_device (default 0), audio_device (-1 or omitted uses the system microphone), and volume (microphone gain, 0 to 1). Timed saved exports capture microphone audio unless options.audio is false. options.test-pattern uses synthetic video instead.
  • render_visualization: visualization is waveform or fft; optional Audio selects { "type": "test" } (default), { "type": "file", "path": "..." }, { "type": "file", "data_base64": "...", "mime_type": "audio/wav" }, { "type": "url", "url": "..." }, or local { "type": "microphone" } with top-level audio_device: 0 and optional volume (0-1). Supplying audio_device or volume without an audio source selects microphone input. Both fields are unavailable with --server.

Rendering tools accept Options Module, timeout_ms (1000–60000, default 45000), and a local-only optional output_path. Restricted HTTP mode accepts output_format instead and automatically produces a temporary download.

{
"name": "render_file",
"arguments": {
"path": "/home/me/image.png",
"options": {
"width": 100,
"height": 40,
"color-mode": "none",
"snapshot": true,
"snapshot-delay": 0
}
}
}

For uploaded media, the client can pass an HTTP(S) media URL to render_url or read and base64-encode the bytes for render_file; an attachment in a conversation is not automatically accessible to an MCP server. Decoded uploads are limited to 16 MiB; request bodies to 24 MiB; returned ASCII to 8 MiB.

The shared option schema is generated from the CLI registry through an explicit exposure table in src/mcp-server/request.c and the shared src/common/options/json.c adapter. It covers palette/characters, color/filter/render mode, dimensions, transforms, effects, FPS, snapshot/delay, seek/loop, test pattern/audio, audio processing, and render styling. Local mode additionally exposes custom render fonts and yt-dlp options. Unsupported/unknown arguments are rejected, including arguments hidden from the hosted schema.

Defaults are 100×40, monochrome, snapshot enabled with delay zero, splash and speaker playback disabled. snapshot-delay measures capture duration after the first rendered frame, matching CLI semantics; it is not time from receipt of the tool call. Use seek to choose a media timestamp. Snapshot false is bounded by timeout and suitable for finite media; unbounded capture must finish via snapshot or returns a timeout error.

Saved images and videos

Video output automatically chooses a font size to keep large recordings near 1280 pixels per side. Set options.render-font-size (for example, 28) to choose an explicit size; width and height set the character grid. Images retain the 12-point default. Use color-mode for rendered colors, rather than the CLI diagnostic color option.

Set local output_path to an image/video filename. The existing render-file pipeline renders the ASCII grid into the encoded artifact, with format selected by extension. Parent directories must exist. The server stages the encoded artifact in a private directory beside the destination, then publishes with an atomic non-replacing hard link. Existing regular files, symlinks, and destinations won by concurrent writers are preserved. Filesystems without hard-link support return an error instead of falling back to an overwriting rename. Cancellation/failure removes staged artifacts; successful results contain absolute paths in structuredContent.saved_files.

{
"name": "render_visualization",
"arguments": {
"visualization": "fft",
"audio": { "type": "test" },
"options": {
"snapshot": true,
"snapshot-delay": 2,
"render-font-size": 28,
"color-mode": "truecolor"
},
"output_path": "/home/me/fft.mp4"
}
}

In restricted HTTP mode, each successful render is exported automatically. output_format accepts png, jpg, jpeg, bmp, webp, gif, mp4, mov, mkv, webm, avi, flv, ogv, ogg, and 3gp; availability of individual formats depends on the FFmpeg encoders in the build. The default is PNG for a single-frame snapshot and MP4 for a timed or continuous render. GIF output from a media file or URL renders to the end by default, producing animation for video. Set options.snapshot to true for one frame or options.snapshot-delay for a timed clip; the request timeout still applies. For video with source audio, set options.audio to true and snapshot-delay above zero. The response includes download_url and expires_at (UTC RFC 3339) in structuredContent; saved_files contains the same URL. Links expire 30 minutes after publication, and expired files are removed. A missing or expired file returns HTTP 404. Downloads use unpredictable names, but anyone possessing a link can access it until it expires.

The download settings are also available in config.toml:

[mcp]
server = true
transport = "http"
downloads_dir = "/var/lib/ascii-chat/downloads"
downloads_url_prefix = "https://mcp.ascii-chat.com"

The server stores downloads in the platform application data directory under ascii-chat/downloads (XDG data on Unix, Local AppData on Windows). --downloads-dir or ASCII_CHAT_DOWNLOADS_DIR overrides that directory. The default public base URL is http://127.0.0.1:<port> (HTTPS when the listener has TLS). Behind a reverse proxy, set --downloads-url-prefix https://your-domain.example to the externally reachable base URL and route /downloads/ to the server. The server appends /downloads/ to generated links. The prefix is configuration, not derived from untrusted request headers.

ascii-chat mcp-server --transport http --server --address 127.0.0.1 \
--downloads-url-prefix https://mcp.example.com

Results contain content text plus structuredContent with ascii, elapsed_ms, and saved_files. Decoder/render errors use isError: true; JSON-RPC errors cover malformed protocol requests. Each render is isolated in a child mirror process with an explicit environment and no user/system configuration. The parent handles deadlines, output limits, and local cancellation while keeping its transport responsive. Plaintext hosted MCP uses the shared libuv HTTP service, including its HTTP/1.x and HTTP/2 request limits, wakeups, and asynchronous response lifecycle. MCP rendering jobs use the shared renderer request, result, cancellation, and reaping lifecycle; MCP-specific code is limited to JSON-RPC and transport adaptation.

Hosted isolation

--server mode omits device enumeration and webcam tooling and rejects caller-selected paths, microphone access, saved output paths, custom font paths, and arbitrary yt-dlp options. Uploaded bytes use private server-created temporary files. These capability restrictions do not sandbox third-party media decoders or URL extractors: public deployments must run under an unprivileged account/container with no secrets or device mounts and network egress rules blocking private/loopback/link-local/metadata destinations. Enforce those rules on redirected and nested media requests too. Put authentication/rate limits at the reverse proxy if required. Local mode intentionally permits the filesystem and devices of the user running it.

Codex connection

The repository's .codex/config.toml and .mcp.json use the shared HTTP endpoint http://127.0.0.1:27228/mcp. Start the runtime copy with build/bin/ascii-chat-mcp mcp-server --transport http --address 127.0.0.1 --port 27228 (Windows: add .exe). See the ascii-chat-mcp-dev skill for copying builds and restarting it. Chats retain the endpoint across restarts; interrupted requests may need retry.

For a client-managed stdio server instead:

[mcp_servers.ascii_chat]
command = "./build/bin/ascii-chat"
args = ["mcp-server", "--transport", "stdio"]
tool_timeout_sec = 70

The suffixless executable path works on Windows (which resolves .exe) and Unix (which uses the exact filename), without a symlink. For a checkout outside the current project, use its absolute suffixless path. Newly created chats can discover the five tools through this stdio connection. The server must be built before starting the chat.

Claude Code connection

To replace the shared HTTP entry in .mcp.json with a client-managed stdio server:

{
"mcpServers": {
"ascii_chat": {
"type": "stdio",
"command": "./build/bin/ascii-chat",
"args": ["mcp-server", "--transport", "stdio"]
}
}
}

Build the executable first, start Claude Code from the checkout, and approve the project server when prompted. Use /mcp to inspect its connection. This is the same suffixless build path as the Codex configuration; use an absolute path for a server in another checkout.

For a networked server, start ascii-chat mcp-server --transport http --address 127.0.0.1 --port 27228 separately and replace the stdio entry with:

{
"mcpServers": {
"ascii_chat": {
"type": "http",
"url": "http://127.0.0.1:27228/mcp"
}
}
}

Add --server for the restricted cloud tool profile described above. See the Claude Code MCP documentation for project scope and approvals.

Telemetry

MCP uses the ordinary --otel-* options, environment variables, configuration, and process shutdown. ascii-chat.mcp.request spans record bounded method and transport names; ascii-chat.mcp.render child spans preserve parent context across render threads and record the tool, output byte count, and failure category. HTTP responses record status codes and body sizes. Metrics under ascii-chat.mcp.* count requests, rejections, renders, failures, cancellations, deadlines, saved files, and output bytes, with render duration in seconds.

Telemetry attributes do not include media URLs, file paths, uploaded bytes, ASCII content, credentials, or caller-supplied request IDs. Render subprocesses keep their isolated environment and do not export separately; the parent records their job. As with every other mode, test environments prohibit collector export.

Statistics

MCP measurements use the process stats scope and canonical metric mappings in include/ascii-chat/stats/telemetry.def, so each observation feeds both local statistics and OTEL without duplicate counters. HTTP mode supports the = stats viewer, including totals, rates, render duration, and transport details. Use --stats-interval 1 with either transport for periodic summaries. MCP summaries use stderr so stdio stdout stays a JSON-RPC stream; stdio never reads UI keys.

Portable SIMD builds

Migrated from docs/simd.md into the rendered Doxygen topic set.

Portable SIMD builds

Release binaries use a fixed CPU baseline (x86-64 or ARMv8-A). CMake's ASCIICHAT_SIMD_MODE=auto compiles every backend supported by the target toolchain, regardless of the build machine's CPU: SSE2/SSSE3/AVX2 on x86-64, NEON on ARM64, and SVE on Linux ARM64. Scalar is always available.

ISA flags apply only to backend source files. These files are excluded from unity compilation, shared precompiled headers, and LTO. Ordinary code, startup, feature detection, and the dispatch table remain baseline code. Release CPU tuning defaults to portable; native, custom, and explicit x86 microarchitecture profiles deliberately raise the minimum CPU requirement and are for local builds.

PIE compile flags apply only to executable targets. Library objects stay PIC, including vendored archives: ThinLTO can import TLS access into those objects, where PIE would produce relocations that cannot link into a shared library.

The platform layer checks CPUID and OSXSAVE/XCR0 on x86 and Linux HWCAP on ARM. CRC32 uses the same runtime detection with function-local target attributes. Each thread caches an immutable luminance dispatch table. SVE kernels use the calling thread's current vector length, predicated loads, and predicated stores; there is no fixed-size SVE scratch buffer in the dispatched kernel.

Monochrome, foreground, background, and indexed-color formatters share the same output code and call the selected RGB24-to-luminance kernel once per row. This preserves palette selection, ANSI formatting, and run-length encoding across backends. Half-block rendering retains its existing implementation. Legacy architecture-specific renderer entry points remain compiled, but are not the automatic luminance dispatch path.

For diagnosis, set ASCII_CHAT_SIMD=scalar|sse2|ssse3|avx2|neon|sve before starting the process. auto (or an unset value) chooses the highest available backend. Unknown, uncompiled, or unsupported requests safely select scalar. An override never permits unsupported instructions. Debug startup logging reports the selected luminance backend.

Tests

The standalone suite uses the production detector, selector, and kernels without requiring the application's media dependencies or Catch2:

cmake -S tests/simd -B build_simd -G Ninja -DCMAKE_C_COMPILER=clang -DCMAKE_BUILD_TYPE=Release
cmake --build build_simd
ctest --test-dir build_simd --output-on-failure

On Windows run from a Visual Studio developer environment and add -DCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreaded for static CRT linkage. On Linux add -DCMAKE_EXE_LINKER_FLAGS=-static for the emulated compatibility tests. The suite checks every synthetic feature mask, all 16,777,216 RGB inputs per available backend, every row length from 0 to 1025, unaligned buffers, and output sentinels. The static test binary can also be run with QEMU on non-SVE ARM64, at different SVE vector lengths, and on x86 without AVX/OSXSAVE:

cmake -S tests/simd -B build_simd_arm -G Ninja -DCMAKE_C_COMPILER=clang \
-DCMAKE_C_COMPILER_TARGET=aarch64-linux-gnu -DCMAKE_SYSTEM_NAME=Linux \
-DCMAKE_SYSTEM_PROCESSOR=aarch64 -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXE_LINKER_FLAGS=-static
cmake --build build_simd_arm
qemu-aarch64 -cpu cortex-a53 build_simd_arm/simd-test neon
for vl in 16 32 64 128 256; do
qemu-aarch64 -cpu max build_simd_arm/simd-test sve "$vl"
done
qemu-x86_64 -cpu qemu64 build_simd/simd-test sse2
qemu-x86_64 -cpu Nehalem build_simd/simd-test ssse3
qemu-x86_64 -cpu max,-xsave build_simd/simd-test ssse3

Cross-compilation uses Clang with an installed ARM64 Linux sysroot. To compare the actual application's rendered output across backends:

uv run --frozen python tests/simd/smoke.py build_release/bin/ascii-chat auto sse2 ssse3 avx2
uv run --frozen python tests/simd/audit_flags.py build_release/compile_commands.json

Full release validation must also run the application (including rendering and shutdown) and its static-link audit. On macOS, static release means that third-party dependencies are static; required Apple system libraries remain dynamic.

Shared statistics collection

Migrated from docs/stats.md into the rendered Doxygen topic set.

Shared statistics collection

ascii-chat/stats/stats.h provides process-local counters, gauges, duration accumulators, and independent rolling-rate samplers. It does not start threads, instrument modes automatically, or render output. It is available in native debug and release libraries. stats/runtime.h integrates the collector with native modes, transport lifetimes, the shared terminal controller, and periodic stdout summaries.

Recording

Create a scope before starting its workers. Capabilities are copied at creation; supported measurements begin at zero, while unsupported measurements remain unavailable even though their storage is zero. Recording an unsupported metric, an invalid ID, or a NULL scope is a no-op.

stats_capabilities_t capabilities = {0};
stats_scope_t *stats = NULL;
asciichat_error_t result = stats_scope_create(&capabilities, &stats);
if (result != ASCIICHAT_OK)
return result;
uint64_t start = time_get_ns();
result = convert_frame(/* ... */);
time_elapsed_ns(start, time_get_ns()));
if (result == ASCIICHAT_OK)
// Stop and join all producers and snapshot readers before destruction.
stats = NULL;
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:117
struct stats_scope stats_scope_t
void stats_scope_destroy(stats_scope_t *scope)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
asciichat_error_t stats_scope_create(const stats_capabilities_t *capabilities, stats_scope_t **out_scope)
stats descriptor is intentionally a small, concrete record. Fields such as name, unit,...
bool counters[STATS_COUNTER_COUNT]
bool durations[STATS_DURATION_COUNT]

The recording API itself performs no allocation or formatting. Counters and gauges use the platform atomic abstraction without its debug instrumentation. Duration updates use a short scope-local mutex so count, sum, minimum, and maximum are coherent. In debug builds, the platform mutex diagnostics may allocate per-thread tracking storage on first use. Snapshot copies serialize with one another and briefly lock durations; independent metrics are not an application-wide transaction.

Durations measure attempts, including failures, except RTT which only records matched responses. Count successful operations separately. Descriptor functions provide stable names, units, and measurement boundaries. Byte counters mean ACIP header plus payload bytes, excluding TCP/WebSocket/WebRTC framing and encryption overhead. Presented frames mean completed media output, excluding overlays.

Counters are cumulative; gauges are the current value set by their owner. There is no reset API. Unsigned totals wrap at 64 bits; an observed decrease resets a sampler's baseline instead of producing a giant rate. Sampling cannot detect an entire wrap that occurs between observations without a net decrease.

Reading and rates

stats_scope_snapshot() returns a value copy that remains valid after scope destruction. Read capabilities to distinguish unsupported from measured-zero counters/gauges, and observation count to distinguish an empty duration from a zero-duration observation. Min/max in snapshots are lifetime extrema.

Each consumer creates its own sampler, for example:

.window_ns = NS_PER_SEC_INT,
.resolution_ns = 250 * NS_PER_MS_INT,
};
stats_sampler_t *sampler = NULL;
asciichat_error_t result = stats_sampler_create(&config, &sampler);
if (result != ASCIICHAT_OK)
return result;
result = stats_scope_snapshot(stats, &snapshot);
if (result == ASCIICHAT_OK)
result = stats_sampler_update(sampler, &snapshot, &rates);
// Use rates only when result == ASCIICHAT_OK and rates.ready.
// Retain the sampler for subsequent updates; destroy when this consumer stops.
sampler = NULL;
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
struct stats_sampler stats_sampler_t
void stats_sampler_destroy(stats_sampler_t *sampler)
asciichat_error_t stats_scope_snapshot(const stats_scope_t *scope, stats_snapshot_t *out)
stats sampler config keeps the values that move through the subsystem: window_ns, resolution_ns....
asciichat_error_t stats_sampler_update(stats_sampler_t *sampler, const stats_snapshot_t *snapshot, stats_rates_t *out_rates)
asciichat_error_t stats_sampler_create(const stats_sampler_config_t *config, stats_sampler_t **out_sampler)

Call update regularly, including while idle. The first call establishes a baseline. Later calls use actual elapsed nanoseconds and integer deltas before converting to floating point. Duration means use differences of sums and counts, not averages of averages. duration_valid is false when the window contains no observations; it is true for measured zero-duration observations.

History retains samples at least resolution_ns apart. The window starts at the latest retained sample at or before its boundary, or at the oldest available sample during warmup. This avoids inventing interpolated event counts. With regular updates the effective window can exceed the requested window by one retention interval; irregular input may extend it further. elapsed_ns reports the actual interval. ready means a positive interval is available, not that the full configured window has elapsed. Rates reach zero once the retained window contains no activity.

Scope or capability changes, nonincreasing timestamps, or decreasing cumulative values clear history and return ready=false. Gauges may decrease freely. A sampler requires serialized access from its owner; separate consumers never alter one another's history. Its allocation is bounded at creation by ceil(window_ns / resolution_ns) + 2 snapshots, with at most 4096 intervals.

Integration boundaries

Mode adapters own identity, labels, transport, dimensions, and layout. Collection has no automatic parent rollup. Record process lifetime totals at the event source alongside connection-local totals, rather than summing only live clients and losing history on disconnect. Avoid counting the same packet in both a transport wrapper and its caller.

The legacy server report now copies process lifetime ingress/send/drop counters; its averages are explicitly lifetime averages. It no longer derives capture from sent-plus-dropped frames or loses history when a client disconnects. This feature does not introduce protocol messages or export remote measurements.

Native runtime and display

Press = to open statistics in server, client, mirror, discovery, or discovery-service mode. Escape or = returns to the previous view. Tab (or left/right) switches between overview and connection/mode details. Up/down select rows in details; Home returns to the first row. Each page measures its longest body line, full row count, and header/footer. If either terminal dimension is below that requirement, the shared too_small screen shows the required size. Resizing to that size restores the entire page; content is not clipped or scrolled to hide rows. Prompts, help, and interactive grep retain their input. A waiting discovery invitation also accepts =.

A dedicated sampler refreshes at approximately 4 Hz, using a roughly one-second rolling window independently of media FPS. Capture, network transfers, conversion, and recording continue behind the overlay. Only media actually written by the presentation controller contributes to presented FPS and terminal-write duration. Consequently presented FPS goes to zero while stats covers the media screen.

Mode Measurements and details
Server Ingress/output frames, per-transport traffic, ASCII conversion and audio mix timing, codec activity, output video queue depth, per-client dimensions/totals/video drops/audio queue depth
Client Capture, encode/decode, send/receive/presentation, traffic, policy skips and queue drops, audio buffer/underruns, connection attempts
Mirror Capture/conversion/presentation, terminal writes, source/output dimensions, media position/duration, recording frames/timing when enabled
Discovery Media and transport measurements for the current role, setup time/state, reconnect/migration counters; includes WebRTC data channels
ACDS Live sessions/participants, transport traffic, creates/lookups/joins/failures, expirations/rate limits, migration completions/timeouts, session table

Connection details retain at most 64 transport rows; process totals include every transport, including disconnected or undisplayed peers. Mode tables are bounded by the shared 128-line view. Snapshots are value copies; table providers copy under their owners' locks and must unregister before teardown. The TUI labels timings with no observations as not sampled, and timings with no recent observations as idle. Client ASCII conversion is n/a (server) until measured locally. Connection setup displays the last attempt duration, retained across idle windows; its lifetime maximum remains a separate column. RTT is explicitly unavailable: the current heartbeat protocol does not provide uniquely matched round-trip probes. Disabled audio and recording are identified on the overview.

frames_enqueued counts successful queue submissions, including separate fanout submissions. frames_skipped counts intentional presentation policy skips. queue_drops counts queue-capacity frame losses and is a subset of frames_dropped, which also includes processing/output failures. Counters refer to events at their named boundaries, so they are not a frame conservation equation. Send success means the transport accepted the ACIP packet, not remote delivery. ACIP bytes exclude encryption and transport framing, handshakes outside the ACIP helpers, TCP retransmission, ICE/STUN, and RTP audio. They are not wire bandwidth.

Audio underruns/overruns count PortAudio callback flags. Encoded-frame counters refer to H.265 output frames; decoded frames include H.265 and ASCII payload decoding. Recording has separate counters. Conversion time includes work inside the existing conversion entry point. Connection setup measures the TCP/WebSocket connection attempt, or discovery setup through active/failed state. Service timing measures ACIP dispatch through handler return; expiration counts come from actual database deletions. Successful lookup counts describe lookup requests handled, including a normal not-found response.

With --status-screen=false, servers retain keyboard access for the temporary overlay. Console output is suppressed while it owns the terminal; file logging and bounded log capture continue. Closing it restores console output.

For services and redirected stdout:

ascii-chat server --status-screen=false --stats-interval 5
ascii-chat discovery-service --status-screen=false --stats-interval 5

ASCII_CHAT_STATS_INTERVAL provides the equivalent environment setting. Zero (the default) disables summaries. Each ANSI-free stats mode=... line includes lifetime counters, recent per-second rates, gauges, and recent mean durations in milliseconds. Inactive timing windows emit unavailable. When stdout is a file, summary output continues even if an interactive overlay uses stderr.

Validation

The Catch2 suite is test_unit_stats_stats (filter *stats*). It covers capabilities, independent snapshots and consumers, irregular and idle sampling, ring wraparound, duration means, baseline changes, invalid configuration, descriptors, concurrent recording/snapshot reads, disconnect/restart accounting, label sanitization, and debug-registry teardown. Run it on Linux; Catch2 is not supported by the native Windows build.

tests/integration/stats_tui.py runs real processes in Linux tmux terminals: all five modes, TCP/WebSocket/WebRTC media, capture behind the overlay, exclusion of overlay paints from video FPS, resizing, reopening, help/grep input priority, server console restoration, redirected summaries, and shutdown with stats open. tests/integration/stats_terminal.py exercises all five modes with Windows ConPTY (or POSIX PTYs). terminal_prompt.py verifies that = remains prompt text.

uv run --frozen python tests/integration/stats_tui.py --binary build/bin/ascii-chat --artifacts build/stats-evidence
uv run --frozen python tests/integration/stats_terminal.py --binary build/bin/ascii-chat.exe --artifacts build/stats-windows

tests/benchmarks/stats.c measures collection calls against a built library; tests/integration/stats_overhead.py compares an actual mirror process with the overlay closed/open. Measurements depend on build flags, terminal, and hardware.

Terminal captures and measured overhead

These PNGs render the actual ANSI terminal cells captured from running processes by stats_tui.py, using render_stats_capture.py:

Mode Overview Details
Mirror Capture
Client Capture
Server Capture Client table
Discovery Capture
ACDS Capture Session table

The Linux debug build with ASan/UBSan passed all 13 statistics tests and the terminal integration scenario, including real TCP, WebSocket, and local WebRTC media. Native Windows ConPTY checks passed all five modes and prompt input. A Linux release build also passed live mirror collection and redirected server summaries. This is focused validation, not a full repository test-suite result. ASan leak detection was disabled because of existing PCRE allocations at exit. macOS, WASM, audio hardware, and forced host-migration failure scenarios were not validated in this run.

On the Linux sanitizer build, one million calls measured about 16 ns per counter update, 769 ns per duration update, and 2.12 microseconds per snapshot. A separate five-second mirror run at 30 fps used 16% of one CPU core with the overlay closed and 14% open. These are whole-process measurements: covering media output reduces terminal work, so the difference does not isolate collection overhead.

Sync inspector activity

Migrated from docs/sync-activity.md into the rendered Doxygen topic set.

Sync inspector activity

Counts measure operations, not time spent blocked or kernel system calls. For conditions, L/s means waits and U/s means signals plus broadcasts; they are not a balanced lock/unlock pair. Change/s counts actual atomic value changes; other primitive types show -. Rows sort by L/s + U/s descending, with mutexes in detected wait cycles always first. Ties sort by type and name. Total Actions is cumulative: acquisitions plus releases for locks, waits plus signals/broadcasts for conditions, and tracked loads/stores/CAS/RMW uses for atomics (including unchanged stores and failed CAS). Inspector reads do not add to atomic totals. Counts use decimal compact notation such as 57.4k and 1.3m, rounded to one decimal place with trailing .0 omitted. Total Wait is elapsed wall-clock time with at least one thread inside a condition wait, including current waits. Overlapping waiters count once, idle intervals add nothing, and non-condition rows show -. It includes reacquiring the associated mutex before the wait returns. Durations use time_pretty(): 100ns, 255ms, 2.5s, 1:23 for minutes, 2:05:30 for hours, and 37d 2:54 for days and hours/minutes. Trailing fractional zeros are omitted. Timing snapshots never acquire that mutex. Names are capped at 30 columns; the selected full name appears in the footer. State/value uses 12 columns, followed by a two-space break.

Metadata and diagnostics

Logging and allocation attribution use per-thread copies of registry metadata. An atomic revision invalidates each copy after registration/removal. Warm hits, misses and type checks do not acquire the registry rwlock. Copies own their strings; they never pin objects or authorize dereferencing cached addresses. Actual object-state snapshots retain the registry's lifetime protection.

The condition checker scans at the five-second stuck-wait threshold, scheduling earlier existing-wait deadlines and retrying busy snapshots. Already-stuck conditions retain their 500 ms warning cadence. It takes two registry read locks per completed scan. The mutex cycle detector still checks every 100 ms, using fixed, serialized scratch storage instead of allocating lists per thread.

The visible inspector takes a protected registry snapshot four times per second. With it hidden, the controlled mirror run averages 0.4 registry acquisitions/sec from condition checks. Opening it adds approximately four acquisitions/sec.

Rendering and input

Colorscheme readers cache a thread-owned scheme and compiled palette, invalidated by the scheme revision, output mode and detected terminal background. Applying a scheme still serializes writes and appears on the next read.

FFmpeg prefetch waits on frame consumption, seek completion and shutdown notifications instead of polling every millisecond, including at EOF. Empty consumer polls read atomic readiness/error flags without taking the mutex. The producer publishes and checks its next wait predicate in one protected section; its only release/reacquire around work keeps decoding outside the handoff lock. Each delivered frame normally needs one consumer pair, one producer pair, and a condition wait release/reacquire pair. Rewind explicitly wakes EOF sleepers. Pause state is a registered atomic flag, with CAS toggles to preserve concurrent pause-key changes; pause queries acquire no mutex. The source-level seek mutex was only used by audio readers, so it did not exclude seeks. Seek/reset now uses the decoder packet mutex, covering buffered audio too. A seek generation discards pre-seek video decode completions while preserving the current consumer image until its replacement arrives.

Inactive recording submissions return before locking. When recording is active, audio_recording protects the mixer and its lifetime; the atomic fast-path hint is always checked again under that lock. Other static locks are named audio_visualization_history and fftw_planner for their actual purposes.

Mirror's latest-frame queue waits for notification with a bounded 100 ms timeout instead of polling every millisecond. Three reusable frame slots keep capture, queued and displayed images distinct; recording retains shared owning buffers. Display-owned resize/flip/filter images and terminal assembly storage are reused until dimensions/capacity change. Typical render rows use invocation-local stack scratch, with a heap fallback for widths above 512. Mirror reuses its ASCII output buffer. Three reference-counted UI snapshot slots copy each submission directly into owned storage; an in-flight reader prevents its slot from being reused. Capacity growth, effects and recording retain tracked allocation paths.

Local file playback refills its 150 ms audio queue below 100 ms instead of waking on every device callback. Capture/AEC keeps its 10 ms cadence. File-only transmission produces complete 20 ms audio frames on the media clock, without acquiring the device wakeup guard. Audio callbacks wake the worker only for capture/AEC or local monitoring.

Connected media ownership and names

Inspector name Protected state or notification
shared_media_buffer_pool Shared media buffer free lists, allocation budgets and accounting
reserved_control_buffer_pool Buffer capacity reserved for handshake/error/control traffic
audio_processing_wait_guard Device-driven audio worker sleep/shutdown coordination
audio_processing_wakeup New capture/render work, local-playback refill or shutdown
connection_outgoing_packet_queue Outgoing packet admission, ordering, priority, budget and completion state
outgoing_packet_ready_or_done Queue became nonempty, synchronous control completed, or connection stopped
tcp_packet_io_lifetime_guard Receive queue ownership and stream lifetime during transmission/close

Connection-owned packet slots retain at most eight buffers of at most 256 KiB in each receive, outgoing-plaintext and backend-write cache. Larger owners are returned immediately; all retained capacity remains charged to the process buffer budget and is released at connection teardown. Held receive references prevent a slot from being reused. Sharing and releasing nonfinal references use atomic reference counts; the final release still serializes pool accounting. Exclusive receive owners decrypt in place, preserving the nonce until authentication finishes; shared or borrowed envelopes retain the allocation fallback. Framing, ciphertext, video-encoder and capture-image workspaces grow only when needed. Capture reuses the same processed image for paused playback.

Native asynchronous transports already own a bounded outgoing queue, so their audio capture worker submits there directly instead of waking a second sender queue. Two 20 ms Opus frames normally share one network batch, with a 40 ms partial-batch deadline. Device processing stays independent of video FPS. Backpressure reads use the backend's atomically published queued-byte count; they no longer acquire the TCP guard to poll the stream. Conditions notify on empty-to-nonempty transitions and actual synchronous completions instead of broadcasting after every asynchronous submission. Per-frame debug messages are rate limited; log-history serialization remains for messages actually retained. ASCII decode output is also retained by the client's receive worker; compressed and plain frames share the same callback and checksum validation.

Inspector output is assembled in a fixed 64 KiB presentation-worker buffer, then flushed as a frame with terminal synchronized-output markers. Exceptional oversized frames flush in chunks. Rendering adds no allocation or mutex dependency; terminal writes scale with frames/chunks rather than table rows.

Loop/seek cancellation stops the old packet reader before clearing the seek interrupt flag. The seek itself remains interruptible by application shutdown, and clears only a cached AVERROR_EXIT from the canceled read. Keeping the seek flag set during av_seek_frame() could cancel the seek's own I/O and make a later file loop fail as a background decoding error.

The outgoing queue still needs producer/consumer handoffs and condition wait release/reacquisition. Incoming audio and video also cross the I/O/receive-worker boundary. These operations scale with packets, including audio delivered independently of video. A displayed acquisition is not a kernel call: Windows first tries TryEnterCriticalSection, blocking only when that attempt fails.

Controller geometry and screen coverage are atomically published for input readers; queries never borrow a screen snapshot or acquire its mutex. Empty input probes decode terminal replies and retain the next key in order before taking the routing mutex. Buffered keys, paste state and editor deadlines still use serialized routing. Mirror's idle input cadence is 10 ms; static presentation geometry checks are bounded at 100 ms and new frames wake presentation immediately.

Verification

tests/integration/sync_tui_modes.py checks inventories, navigation, resizing, colors and activity in mirror, connected client and discovery modes, with generated changing video and audio. Its artifact directory contains actual PTY cells as PNG/text, raw ANSI, logs and per-mode activity JSON. These controlled 15 FPS results vary with device callbacks, workload and logging verbosity.

Native regressions cover cache removal/reuse, empty lookups, zero-lock warm palette reads, allocation-free deadlock scans, frame-slot ownership, resize workspace output equivalence (including wide heap fallback), 1,000 warmed ASCII conversions and UI submissions with an older snapshot held in flight, non-consuming input probes, Escape timing, paste/editor routing and zero-lock idle UI queries.

A verified 15 FPS mirror sample, with the inspector open, measured approximately:

Primitive Acquisitions/sec (or condition waits/sec)
named_registry_lock 4 (0.4-0.5 across a hidden interval)
colorscheme 0
shared_media_buffer_pool 0
timer_manager 0
display 47
ffmpeg_prefetch about 45
queue_not_empty 16
debug_memory 0 after warm-up
audio_processing_wait_guard 31-39
ui_controller 31
ui_input 0

The display queue performs roughly three acquisitions per video frame. Warm mirror rendering no longer allocates ASCII output or UI snapshots per frame. Connected client/discovery workloads additionally own network and audio buffers; the zero mirror buffer-domain result is not a claim about those transport paths.

Sync primitive inspector

Migrated from docs/sync-tui.md into the rendered Doxygen topic set.

Sync primitive inspector

In a debug build, press 0 during a session to open the live inspector. Press 0 or Escape to return to ASCII art. The 0 inspector, ? keyboard help, ] logs and o media input replace each other. Switching directly between them does not expose a media frame, and closing one never restores an older TUI. In the media editor these keys switch screens; paste paths or URLs containing shortcut characters to insert them as text.

  • Up/Down select the previous/next object, crossing page boundaries.
  • Left/Right move one page, preserving the row where possible and clamping at the endpoints. They preserve the selection when there is no previous/next page.
  • Home selects the first object on the first page, even from another row on that page.
  • End selects the last object on the last page. Repeated Home/End presses stay at the endpoint.
  • Resizing recalculates pages around the selected object.

The header reports the total objects, current page, selected item, sample age, and counts by type: M (mutex), RW (rwlock), C (condition variable), and A (integral/boolean/pointer atomic). The footer shows the selected object's registration location, address, owner/waiter, value, and last-operation age. Blue separators use UTF-8 line characters when UTF-8 is enabled and supported, or ASCII hyphens otherwise. Colors follow the configured log palette and --color-mode none disables them.

The list contains every live synchronization object in the named registry, including idle objects. It grows dynamically and is paginated; terminal height does not truncate the inventory. Mirror normally has fewer objects than a connected client because it does not create the connection's workers, transport, queues, and authentication state. File playback, audio, and active UI screens also affect the count. Destroyed objects are removed. When an initializer and its owner both register a primitive, the inspector counts that address once and displays its latest registration name. Child names include a registration ID so multiple audio buffers remain distinguishable.

This is a registry of instrumented ascii-chat primitives, not a scan of process memory. Raw C11 atomics, synchronization inside third-party libraries, and unregistered implementation bookkeeping do not automatically become entries. Embedded condition/rwlock counters are displayed in their parent object's state. New atomic_t/atomic_ptr_t session fields need explicit registration and unregistration before their storage is released. Register process-lifetime atomics after the named registry has initialized. Mutex/condition/rwlock initializers register their wrappers automatically. Audio and generic ring buffers register their atomic fields during creation and remove them on destruction.

Run the native regressions and live-mode checks with:

cmake --build build --target ascii-chat test-sync-regressions
uv run --frozen python -m pytest tests/python/tests/integration/sync --sync-probe build/bin/test-sync-regressions.exe
uv run --frozen python tests/integration/sync_tui_modes.py --binary build/bin/ascii-chat.exe --artifacts build/sync-tui-evidence
uv run --frozen python tests/integration/tui_switching.py --binary build/bin/ascii-chat.exe

The live-mode test uses generated video/audio and loopback services. Its optional PNG exports render the captured PTY cells, alongside the exact ANSI stream and plain text; they do not require access to the user's terminal or webcam.

Shared native and browser test patterns

Migrated from docs/test-patterns.md into the rendered Doxygen topic set.

Shared native and browser test patterns

--test-pattern and --test-pattern 0 select the animated gradient and translucent square. --test-pattern 1 selects rainbow stripes and a wrapping white circle. Both also accept =0/=1. Omitting the flag leaves normal source selection unchanged; 0 means the first animation, not disabled. The option is available in mirror, client, and discovery modes.

ascii-chat mirror --test-pattern
ascii-chat mirror --test-pattern 1 --color-mode 256
ascii-chat client localhost --test-pattern=0

Test patterns are useful for checking the whole display path without a camera or media file:

# Check a narrow terminal and force a predictable renderer.
ascii-chat mirror --test-pattern --width 80 --height 24 --color-mode 16
# Capture one frame for a regression fixture.
ascii-chat mirror --test-pattern 1 --snapshot --snapshot-delay 0 > pattern.txt
# Exercise a remote session's receive and render path with synthetic video.
ascii-chat client localhost --test-pattern --audio=false --fps 10

WEBCAM_DISABLED=1 remains a boolean enable switch; with default configuration it enables pattern zero. Existing boolean [Webcam Module] test_pattern = true/false configuration remains supported; integer 0 or 1 enables the selected animation. CLI selection overrides configuration/environment values.

The browser maps ?test to pattern zero and ?test2 to pattern one. ?test2&testCadence explicitly enables the full-height Gray-code diagnostic overlay; ordinary ?test2 now shows its stripes and circle.

Implementation

lib/video/anim/test_pattern.c owns the RGB animations, a high-contrast pixel-lettered test label, and optional reusable RGBA output. Each media source/canvas has an independent renderer and reusable image buffers. Its public API takes elapsed milliseconds, making animation speed independent of capture FPS and allowing deterministic comparisons. Native sources use a monotonic clock. Geometry adapts below the former Canvas minimum shape sizes so the minimum 20x10 terminal can still show the shapes and colors.

src/web/bindings/test_pattern.cpp binds this same implementation to the WASM modules. TypeScript only copies/uploads the generated RGBA frame and manages source lifetime. The mirror consumes the returned frame without reading the canvas back.

The existing terminal palette helpers are shared by the normal render pipeline. rgb_to_256color now compares the nearest nonuniform xterm cube entry with the nearest grayscale entry, including exact black and white. get_256color_rgb supplies the inverse palette lookup; the existing 16-color helpers supply the other direction. Palette expansion uses the standard reference colors (the first 16 actual terminal colors may be themed).

Recorded verification (2026-10-09)

The C/WASM output was compared against the former Canvas implementation before removing the JavaScript reference and dedicated browser tests. The retained screenshots document that verification:

These earlier comparisons used bundled DejaVu Sans Mono labels. The current renderer instead draws a larger lowercase test centered in the image, using black integer-sized pixel strokes with no backing box. The letters form negative space after ASCII conversion; labels are omitted when the source is too small to fit them. Both native and browser sources use the same label.

Both visible patterns sustained approximately 60 materially changing ASCII frames per second for 10 seconds in a 1920x1080 browser viewport. Application screenshots show the warmed-up counter: mirror zero, mirror one.

Native source images: pattern zero, pattern one. Native CLI and shared-library checks cover selectors/defaults, 30 snapshots, legacy environment inputs, palette mapping, independent sources, resize, and invalid input. The config loader was separately verified with true, false, 0, and 1 from both initial enable states (eight cases); the native unit regression calls the loader directly. The previous CLI check only checked exit status and did not establish that the requested config file was loaded. Recorded results.

Native verification

cmake --preset default -B build
cmake --build build --target ascii-chat
uv run --frozen python tests/platform/probe_pattern.py --binary build/bin/ascii-chat.exe --library build/bin/asciichat.dll

Catch2 tests require a supported platform; Windows verification uses the actual shared library. Native PNG encoder initialization fails in this environment, so the native evidence images were captured directly from the library.

Browser WASM bindings

Browser WASM bindings

The mirror and client modules expose the C implementation through the C++ adapters in src/web/bindings/. Embind generates the declarations in web/packages/shared/src/wasm/generated/ from those adapters. The adapters are only compiled for WASM; native APIs remain C APIs. wasm-build.mjs copies the declarations from both builds and records their hashes alongside the WASM artifacts. Rebuild and publish both modules together after changing a binding.

Browser code should prefer the shared TypeScript facades and generated binding types. SessionUiBinding, MirrorFrameBinding, AsciiRendererBinding, AudioProcessorBinding, OpusCodecBinding, ClientSessionBinding, and BrowserSessionBinding own their C resources. An Embind object must be deleted once after its last use; facades such as the renderer lifecycle and BrowserSession.close() make repeated cleanup safe. Deleting a client session releases its handshake state; browser host state also releases its clients and transports together. The C options and mirror initialization functions remain module-local, so they must be initialized before creating objects that use them. An object belongs to the WASM module and worker that created it; do not transfer it or use it after that module is cleaned up.

Strings are copied at the boundary. Frame and audio inputs are copied into reusable WASM-side storage. Renderer pixels and encrypted packets are copied into JavaScript-owned arrays before returning to callers, including before a peer output queue entry is released. No returned array is a borrowed view of WASM memory, so it remains usable after a subsequent call, heap growth, or object disposal. The framebuffer copy takes an existing Uint8ClampedArray so the canvas path can reuse its ImageData allocation. Do not retain a typed_memory_view across a call that may grow memory or across asynchronous work.

Client bindings are grouped by responsibility: networking.cpp owns connection setup, handshake, packet conversion, and QUIC transport operations; common/opts.cpp handles settings conversion; client_frames.cpp validates and sends frames. discovery.cpp binds discovery while networking.cpp binds handoff, session_host.cpp binds the shared session host, and av_state.cpp owns asynchronous media lifecycle state. Their bindings call their native APIs directly. Common byte copies are shared, and these file boundaries do not change the JavaScript API. The key parser and crypto configuration accept temporary byte arrays. Their C++ adapters clear secret scratch buffers after the C call, and TypeScript clears its temporary arrays in finally. The parser worker continues to unlink its temporary SSH-key file. JavaScript strings and copies owned by browser APIs cannot be reliably wiped. C error snapshots are copied into JavaScript values before reporting them.

Browser video upload probes the exact HEVC and H.264 Annex B configurations with no hardware preference, allowing WebCodecs to choose a supported hardware or software encoder before automatic selection falls back to raw pixels. Explicit codec requests still fail when that codec is unavailable.

Embind is the browser-facing API, including options and host control. The browser renderer owns its SessionUiBinding directly and deletes it when the renderer is released; browser key conversion stays with the renderer. AsciiRendererBinding exposes dimensions() and render(text, zalgo), returning a fresh JavaScript-owned pixel snapshot for each successful render. Render failures remain available through Errors even when construction succeeded. The npm package exposes CanvasRenderer for frame conversion and canvas rendering. Callers can pass a stable source identity to CanvasRenderer.render(); changing that identity resets temporal history. Frame dimension, renderer, render-mode, and palette changes also invalidate history. Call reset() when a seek or other discontinuity occurs within the same source. Options use OptionsBinding.patch({ width: 80, height: 40 }, revision) for one validated atomic update and OptionsBinding.read() for an owned snapshot object. Pass -1 to accept any revision; stale revisions and invalid fields reject the entire patch. The TypeScript options facade supplies the default revision and returns the committed snapshot. The client and mirror initialization bindings accept an options object using the same field names and atomic validation; they initialize native mode defaults before applying that object. No shell-style argument parsing is involved. C functions used by adapters are declared in the corresponding web headers, which their implementations include as well. Emscripten's filesystem remains available for temporary key files; the current heap view is used only to detect input arrays that alias growable WASM memory. Keep high-frequency buffers preallocated where practical, and test any additional copies in the actual worker or rendering path.

The client, mirror, and standalone renderer links enable Binaryen's memory-packing pass. It replaces long zero-filled passive TLS data ranges with initialization operations, keeping the modules small while retaining per-thread initialization and the renderer's allocation-free scratch pools.

The standalone ascii-chat renderer package uses shared Embind frame bindings and options in src/web/bindings/ and src/web/common/ and is built by the separate renderer-web target. It produces an independently initialized WASM module and npm package rather than adding another site asset. Its Embind session object runs native cleanup in its destructor when the TypeScript facade is disposed. Its README documents its TypeScript API, ownership, browser isolation headers, build, and real-browser performance test.

Windows build performance

Migrated from docs/windows-build-performance.md into the rendered Doxygen topic set.

Windows build performance

The native build keeps the Debug sanitizers enabled. Performance measurements should use the same sources, compiler, dependency SDK and build configuration, with other builds idle. A clean build with ccache disabled measures compilation; a clean build with a populated cache measures cache restoration. An unchanged Ninja invocation measures neither.

Build concurrency

On the Ryzen 7 5800X workstation, clean native builds took 89.1 seconds with eight jobs, 97.0 seconds with twelve, and 107.0 seconds with sixteen. These are individual measurements, not a guarantee for other machines or workloads.

Windows Ninja builds default to a compile pool matching physical cores when there is no explicit parallelism setting. An existing CMAKE_BUILD_PARALLEL_LEVEL or CMAKE_JOB_POOL_COMPILE setting is respected. Configure-time environment changes do not persist into a later terminal process; the Ninja pool does.

For this workstation, use cmake --Build System Build System --target ascii-chat --parallel 8. To persist that limit in an existing build directory with a different global environment setting, configure with:

cmake --preset default -B build `
-DCMAKE_JOB_POOLS=asciichat_compile=8 `
-DCMAKE_JOB_POOL_COMPILE=asciichat_compile

Unity builds

cmake --preset windows-unity -B build
cmake --build build --target ascii-chat --parallel 8

This is a sanitized Debug build. On Windows the unity option batches project library sources as well as application mode sources. Vendored sources stay separate so DLL export filtering retains their source paths. Library batches contain four files; the executable uses CMake's normal batch size.

The first unity experiment took 72.7 seconds versus 89.1 seconds without unity. Rebuilding an individual source can require recompiling its batch, and source name or macro conflicts can arise as code changes. Ordinary development builds therefore keep unity disabled by default. Switch back with:

cmake --preset default -B build -DASCIICHAT_ENABLE_UNITY_BUILDS=OFF

Export generation and headers

DLL export generation scans all active object files in one llvm-nm invocation using a response file. PCH files and vendored objects are excluded, filename headings are discarded, and extraction failures stop the build. Bulk filtering and one output write avoid per-symbol file operations. A comparison of the same 338 manifest entries produced the same 2,694 exports in 0.39 seconds instead of 27.5 seconds.

Clang time traces showed roughly 0.8–1 second of Windows-header parsing in sampled audio, crypto and application C sources without PCH. Existing PCH coverage made that cost much smaller in covered sources. Extending PCH to more modules created a C++ macro conflict; a C-only variant compiled, but its full build took 104.2 seconds and did not demonstrate a benefit. The existing coverage was retained.

Later validation builds overlapped unrelated workstation workloads, so their wall-clock times should not be treated as a controlled speed comparison.

Compiler cache

Native launchers pass max_size=12G Compression Module=true compression_level=1 directly to ccache when its installed version supports configuration arguments. PCH targets also pass sloppiness=pch_defines,time_macros and Clang's -fno-pch-timestamp. This avoids launching one or two extra CMake processes per source file. Older ccache versions retain the environment-launcher fallback; the Emscripten compiler wrapper remains unchanged.

A full native unity build with an isolated empty cache took 90.9 seconds. After cleaning all objects and rebuilding, all 211 compiler calls were direct cache hits with zero misses, and the build took 18.2 seconds. This includes restoring objects, regenerating exports and linking; it is not an unchanged-build timing. These two runs also switch from the old environment launchers to the direct native launchers, so their timing combines cache hits and launcher savings.

The C/C++ PCH regression and Windows export tests can be run separately from Catch2:

uv run --frozen python -m pytest tests/python/tests/cmake/test_ccache_pch.py
uv run --frozen python -m pytest tests/python/tests/cmake/test_windows_exports.py