ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
Audio Processing

🔊 Audio capture, playback, and multi-client mixing

🔊 Audio capture, playback, and multi-client mixing

Audio system with PortAudio integration and multi-client audio mixing with ducking.

Audio channels

Migrated from docs/audio-channels.md into the rendered Doxygen topic set.

Audio channels

All call encoders and decoders use stereo Opus. Speech uses centered input at 32 kbit/s; stereo microphones and media use 128 kbit/s. Internal PCM is interleaved stereo at 48 kHz, independent of device layouts and rates. PCM counts include both channels; codec frame durations are measured per channel.

Microphones

Use --list-microphones to choose a device. A multichannel device can still be used for mono speech. The device opener tries supported layouts and routes the selected input before resampling, echo cancellation, and microphone enhancement.

# Stereo microphone, or the first pair on an audio interface
ascii-chat client --microphone-index 2 --microphone-channels 2
# A single microphone connected to input 3 (indices start at zero)
ascii-chat client --microphone-index 2 --microphone-channel 2
# Interface inputs 3 and 4 as a stereo pair
ascii-chat client --microphone-index 2 --microphone-channel 2 --microphone-channels 2
# Explicitly average all available inputs to centered mono
ascii-chat client --microphone-index 2 --microphone-channel -1

The same options apply to mirror and discovery modes and have corresponding ASCII_CHAT_MICROPHONE_CHANNEL and ASCII_CHAT_MICROPHONE_CHANNELS environment variables. The default selects input zero as mono speech. A microphone array's physical channels are not automatically treated as a stereo pair. Prefer its processed speech endpoint when available. Invalid selected pairs fail before opening a stream.

The browser device dialog offers Mono speech, Stereo pair, and a first input number starting at one. Browser support for exposing individual interface inputs varies. A browser-provided single channel stays centered. Browser AEC runs on microphone capture; shared C/WASM enhancement processes the microphone before stereo screen/media audio is mixed in.

Playback and media

  • Mono microphones are centered in both playback channels. Stereo sources retain their left/right separation through resampling, mix-minus, encoding, and recording.
  • Mono-only speaker devices receive a downmix. Multichannel outputs use the first stereo pair and silence the other outputs.
  • Clients advertise stereo support with AUDIO_CAP_STEREO. Call encoders and decoders default to two channels, and servers always send stereo output. There is no legacy-peer mono fallback.
  • Speech filters maintain independent channel state. Stereo gain control, compression, and gating use a shared detector to preserve channel balance.
  • Recordings retain stereo. Waveform/FFT displays downmix only their analysis copy.

Hardware-free validation

tests/unit/audio/stereo_test.c uses generated signals to check routing, resampling across callback boundaries, stereo codec defaults and explicit mono downmixing, stereo dynamics, jitter frame alignment, mix-minus, AEC buffer sizing, and recording timestamps. tests/contracts/audio/device_test.c simulates the PortAudio boundary while running the production callbacks and worker, including stereo-only microphones, mono speakers, and four-channel interface routing. Browser worklet tests generate independent microphone and media inputs.

tests/python/tests/integration/stereo/test_audio_channels.py generates different tones in each channel and checks a real client/server call, including the received stereo WAV. Pass --artifacts-dir DIRECTORY to retain its logs and audio. The Chromium proof at web/web/tests/wasm/stereo-audio.mjs runs the real worklet, worker, C/WASM DSP, and Opus codec with generated microphone and media tracks. Run it against a local Vite server after rebuilding the WASM artifacts.

tests/audio/probe_aec3_echo.py LIBRARY --stereo checks independent playback channels, delayed synthetic echoes, and near-end speech while echo is present. The default invocation retains the mono regression.

These checks do not require a stereo microphone. Physical driver behavior and speaker-to-microphone acoustics still need hardware validation.

Audio reliability and validation

Migrated from docs/audio-reliability.md into the rendered Doxygen topic set.

Audio reliability and validation

Opus is the wire codec at 48 kHz with 20 ms packets. Native and browser paths use stereo codecs for centered speech and stereo media; see audio channels for device routing, stereo negotiation, and hardware-free regression coverage.

Behavior

  • Microphones use the speech Opus application at 32 kbit/s. Media and generated test audio use the audio application at 128 kbit/s. Native encoders share checked bitrate/VBR/DTX configuration; DTX is off by default. Both explicit client and discovery paths select this profile using the opened media source: video-only media with automatic microphone fallback stays in speech mode.
  • Decoded playback is no longer noise-gated. Quiet media is preserved; microphone capture processing, including the default spectral stage, remains separate.
  • Playback starts with 60 ms buffered audio. Actual underruns raise the refill target by 20 ms, bounded at 160 ms; stable playback lowers it toward the initial target. Short tails fade out and refilled playback fades in.
  • Bounded sample interpolation compensates for independent device clocks, up to 1000 ppm. Capture queues remain sample-exact.
  • Invalid Opus frames can use decoder concealment instead of abandoning the rest of their batch. This is not recovery of missing transport packets.
  • Configuration fields now say milliseconds where milliseconds are actually used. The echo-filter hint remains reserved; AEC3 controls its own filter configuration.

Reproducible compiled-library checks

Install NumPy for the Python interpreter, build the native shared library, then run:

uv run --frozen python tests/audio/probe_opus_profiles.py PATH_TO_SHARED_LIBRARY
uv run --frozen python tests/audio/probe_playout_recovery.py PATH_TO_SHARED_LIBRARY
uv run --frozen python tests/audio/probe_spectral_integration.py PATH_TO_SHARED_LIBRARY
uv run --frozen python tests/audio/probe_aec3_echo.py PATH_TO_SHARED_LIBRARY

The library is build/bin/asciichat.dll on Windows, build/lib/libasciichat.dylib on macOS, and build/lib/libasciichat.so on Linux. ASan builds loaded into Python require the matching sanitizer runtime preloaded.

The checks cover ten accelerated minutes at each of -200/+200 ppm, bursty 10–40 ms delivery, actual underrun/refill, restart, unchanged capture queues, independent mixed recipient streams, the production capture pipeline, quiet playback compared sample-for-sample with an independent Opus decoder, decoder concealment, and AEC3 echo-only/double-talk signals.

Earlier mono baseline measurements

Native builds and compiled audio checks passed on Windows, Intel macOS, and Linux. The clock-skew queues stayed within 2399–3361 samples without underruns. The deterministic acoustic model measured approximately 16.7 dB and 22.8 dB echo reduction for 40 ms and 100 ms echoes; near-end correlation was 0.976 and 0.937. These synthetic results are not physical-room certification.

A five-minute Windows ↔ Intel Mac call used generated test audio on both ends and an SSH-forwarded TCP connection. Both clients exited 0 and the server stayed running. Received PCM contained 293.84 seconds on Windows and 293.26 seconds on macOS at 48 kHz, with finite nonzero samples. Startup and shutdown account for part of the difference from wall time; these recordings do not prove gap-free speaker output. Recordings are local test artifacts and are not committed.

A headless Chromium browser connected over WebSocket to the updated native server alongside a native TCP client. With generated input enabled, a 15-second measurement sent 725 browser Opus frames and played 739 received frames (709,440 samples), with zero reported playback underruns and no page errors. The browser screenshot showed a connected client with active capture/playback levels. Canonical client/mirror WASM artifacts were rebuilt from this source and their manifest was regenerated and verified before the check.

Boundaries

The packet format still has no sequence/timestamp contract for unreliable audio; FEC and a lossy transport require a separate protocol change. Physical Bluetooth, device unplug/replug, speaker-to-microphone AEC, and overnight soak coverage are not established by the synthetic tests or the five-minute call. The SSH Mac test intentionally bypasses microphone permission restrictions with generated audio.

FFTW spectral audio processing

Migrated from docs/audio-spectral.md into the rendered Doxygen topic set.

FFTW spectral audio processing

Shared microphone processing

Native and browser clients use audio_processor_t (audio/processor.h) for the same PCM enhancement: spectral denoising, gain control, high/low-pass filters, optional noise gating, compression and soft clipping. Configuration is explicit; the processor does not read CLI options, capture devices, encode Opus or send packets. Each instance has one processing owner. Processing accepts arbitrary block sizes and in-place buffers, with no allocations or locks in the hot path. Gain metering follows the sample clock so changing callback sizes does not change the result. Spectral AGC/compression replace their traditional equivalents. The embedded BSD-licensed RNNoise model is also available for 48 kHz capture. It runs after native AEC3 on complete 480-sample mono frames; stereo capture derives one suppression envelope and applies it to both channels. The model is compiled into the audio library, so the realtime path never loads a model file or performs filesystem/network work. Other sample rates retain the existing spectral path. Client-like modes expose this independently as --reduce-noise (enabled by default) or --reduce-noise=false; ASCII_CHAT_REDUCE_NOISE is the matching environment variable. Test audio continues to bypass microphone enhancement.

The native client first runs AEC3 using its actual speaker playback reference, then calls the shared processor. Browser microphone capture requests native getUserMedia echo cancellation, with browser noise suppression and gain control disabled to avoid applying those effects twice. An AudioWorklet transfers bounded, reusable 20 ms PCM buffers directly to a dedicated worker running the shared C processor and Opus encoder. Audio processing does not run on the UI thread. The worker uses its own WASM instance and codec state, independent of playback. Synthetic test audio bypasses microphone enhancement.

The native server separately performs participant mixing, crowd scaling, compression and clipping. Server spectral processing remains opt-in. A server mix does not replace microphone enhancement or local echo cancellation.

Browser AEC must be assessed with real speakers and microphones, including simultaneous speech and output-device changes, because received audio is rendered through Web Audio rather than an incoming WebRTC audio track. Requested constraints and getSettings() alone do not measure echo removal. A WASM AEC3 backend should only replace browser AEC if acoustic testing shows a need; running both cancellers on the same microphone is not the intended configuration.

tests/audio/probe_processor.py verifies the compiled PCM processor's callback size invariance, reset, in-place processing and media bypass, and can emit raw float32 native/WASM comparison fixtures with an optional output directory.

Microphone spectral noise reduction is enabled by default. Media files and --test-audio bypass microphone processing. When microphone and media are mixed, media samples are added after the microphone processor. Other spectral effects remain opt-in.

ascii-chat client localhost --audio=true
ascii-chat client localhost --spectral-audio=false

Server mixing does not apply spectral processing by default. In server mode, --audio-spectral-mixer=true explicitly enables processing of the entire mixed output, including any media/test sources. Discovery hosts do not support this option. This is separate from --spectral-audio, which controls microphone capture only. Enabling both adds both processors' latency. Existing server configurations that used --audio-spectral=true for mix processing must switch to the new mixer flag. The microphone flag is now --spectral-audio (ASCII_CHAT_SPECTRAL_AUDIO in the environment).

Option Effect
--audio-fft-size 512/1024/2048 Frequency resolution versus delay; default 1024
--audio-spectral-gate=false Disable adaptive per-bin gating
--audio-multiband Four-band compression at 250, 2000, and 8000 Hz
--audio-adaptive-eq Slowly balance band energy, bounded to +/-3 dB
--audio-spectral-agc Spectral RMS gain control, bounded to 0.25–4x
--audio-pitch-correct Experimental monophonic correction to the nearest semitone (capture only)

The normal ASCII_CHAT_... environment variables and registry configuration apply. The terminal FFT visualization is enabled with --fft. It uses the shared FFTW backend and defaults to a dB range of -62:-6, which is intended to keep ordinary speech/music visible while still showing quieter background audio. Use --fft-scale linear, --fft-scale log, or a custom dB range such as --fft-scale -72:-3; custom ranges must be between -120 and 0 dB and span at least 12 dB. The FFT size is validated before audio startup. Effects are selected when creating a pipeline; these are startup settings, not live controls.

Processing contract

The mono processor uses double-precision FFTW transforms, a periodic Hann window, 75% overlap, and weighted overlap-add. It accepts arbitrary block sizes and in-place buffers. It returns exactly the input sample count with exactly one FFT-size of latency: 10.67/21.33/42.67 ms at 48 kHz. Feed that many trailing zeros to flush a finite recording. With all effects disabled, it reconstructs the delayed input. Turning off --spectral-audio bypasses the processor entirely, without added delay.

Plans and buffers are created before capture starts. Planning/destruction is serialized because FFTW's planner is shared; processing uses no allocations or locks. Each processor has one owner thread. Each mixer recipient has its own history, and removing a recipient resets that history. Mixer access remains serialized to protect mutable DSP state.

For stereo capture and stereo server mixes, spectral AGC, multiband compression, and spectral gating are disabled to avoid independent gains shifting the stereo image. Stereo capture instead retains its shared broadband dynamics; stereo mixer output retains the existing mixer dynamics. The spectral EQ remains available.

The gate learns a startup noise estimate over approximately 250 ms, then adapts asymmetrically with attack/release smoothing and a default maximum reduction of 18 dB. A quiet startup helps calibration. It cannot reliably separate stationary speech or music from noise in every situation. EQ is bounded spectral balancing, not calibrated room-response inversion. Pitch correction is a simple phase vocoder for monophonic input; it can color speech and should remain off for normal calls or polyphonic music. Pitch detection requires at least two periods within the FFT window (larger windows cover lower voices).

Existing WebRTC AEC3 remains before spectral capture processing. Enabling spectral AGC or compression disables the corresponding broadband capture stage to avoid stacking it. Server spectral effects follow its existing mixer chain.

The public API is in include/ascii-chat/audio/spectral.h. spectral_config_t exposes crossover frequencies, thresholds, compression ratios, and reduction depth. spectral_spectrum() exposes normalized input amplitudes for monitoring from the owner thread. spectral_pitch_hz() returns the latest detected pitch when pitch correction is enabled. Reset clears overlap, calibration, and effect state.

Build and tests

FFTW3 is a required native dependency. Installers and vcpkg manifests include it; CMake links it unconditionally. Musl/iOS source builds use the pinned FFTW 3.3.10 archive rather than a host library. FFTW is GPL-2.0-or-later; its license is included in docs/third-party/FFTW-COPYING.txt and installed with the runtime. The dependency's license applies in addition to this repository's source license.

cmake --preset default -B build
cmake --build build
uv sync --extra audio
uv run --frozen python tests/audio/probe_spectral.py build/bin/asciichat.dll
uv run --frozen python tests/audio/probe_spectral_integration.py build/bin/asciichat.dll

Pass the shared library path for your platform. The tests call the compiled C/C++ implementation through ctypes; Python is not a substitute DSP implementation. They cover reconstruction, latency, chunk partitioning, in-place processing, frequency accuracy, gating, compression, EQ bounds, pitch correction, gain control, non-finite input, reset, empty-mixer locking, recipient isolation, and the existing AEC3/capture chain. Benchmarks include Python call overhead and report wall time, not whole-application CPU utilization. Catch2 is not supported on Windows.

For physical recording, list device indices with uv run --extra Audio python -m sounddevice, obtain the attributed speech fixture described in the evidence README, then run:

uv run --frozen python tests/audio/record_spectral.py --library build/bin/asciichat.dll --source speech-source.wav --input-device 34 --output-device 27
uv run --frozen python tests/audio/analyze_spectral.py --library build/bin/asciichat.dll --source speech-source.wav

The recorder plays 12 seconds of speech between silent intervals and saves raw microphone and processed WAVs. Choose device indices for your machine. The analysis adds a seeded noise test with a known clean reference, aligns the processor delay, and renders the same-scale spectrogram comparison.

See measured results and recordings. Windows native build and focused tests were run; musl/iOS and other host builds were not exercised. The initial CLIENT_CAPABILITIES mismatch was fixed: pending handshake packets already contain payload-only data and must not have another header stripped. The native two-client TCP test now checks capability lengths, clean client exits, nonzero remote audio, and exclusion of the sender's own audio. It plays human speech through physical speakers into the microphone with spectral capture and server mixing enabled. Explicit --Audio=true avoids toggling the default on state off. To reproduce on a machine with the selected audio devices:

uv run --frozen python tests/manual/probe_network_audio.py --binary build/bin/ascii-chat.exe --output build/network-audio --speech build/audio-evidence/speaker-speech.wav
uv run --frozen python tests/manual/probe_network_audio.py --binary build/bin/ascii-chat.exe --output build/network-encrypted --speech build/audio-evidence/speaker-speech.wav --encrypted
uv run --frozen python tests/audio/analyze_network_audio.py --input build/network-audio --output build/network-report

The encrypted loopback test disables host identity verification only in its child processes so it does not modify the user's known_hosts. This checks encrypted transport, not server identity authentication. Network measurements and recordings are linked in the evidence README.

Repeating diagnostic audio

--test-audio enables audio, replaces microphone/file audio with a generated 20-second loop, and monitors that loop through the selected speakers. It works in client, discovery, and mirror modes; no microphone permission or media file is needed. --speakers-volume controls the local monitor and received audio.

ascii-chat client HOST --test-audio --speakers-volume 0.5
ascii-chat mirror --test-pattern 0 --test-audio --speakers-volume 0.5

The loop contains a soft major arpeggio (0–4 s), a three-tone chord (4–8 s), a 150 Hz–3 kHz logarithmic sweep (8–12 s), quiet broadband noise bursts (12–16 s), amplitude-modulated harmonics (16–18 s), and silence (18–20 s). Soft envelopes avoid abrupt edges; the source peak is below 0.18 full scale. The local monitor mixes with received audio without adding frames to its queue.

The synthetic source bypasses microphone capture/AEC processing, like media input. It tests encoding, transport, server mixing, decoding, and speaker output; it does not verify the microphone or its noise processing. The local monitor is generated separately and is not proof that a peer received anything. Network verification must inspect the peer's received recording.

uv run --frozen python tests/audio/probe_audio_pattern.py build/bin/asciichat.dll --wav test-audio.wav

This checks sample bounds, each section's energy, sweep frequency, silence, repeatability, and arbitrary buffer boundaries at both 44.1 and 48 kHz.

Audio System

The audio system owns device setup and realtime callbacks. Session code selects capture/playback policy and connects the audio context to the client pipeline; the network layer carries batches separately.

Devices

Device enumeration and selection are explicit. The default device is used when no index is supplied. Missing microphones are allowed when playback or a non-device media source does not need capture.

Realtime path

Audio callbacks must remain bounded and allocation-free. They exchange samples with ring buffers/pipelines; encoding, logging, network I/O, and UI updates happen outside the callback. Underruns produce silence and are observable in diagnostics rather than blocking the device thread.

Platforms

PortAudio-backed native builds use the host's available backend. Browser and iOS paths use their platform audio bridges. Do not document a backend as guaranteed merely because it is available on one development machine.

See also
topic_client_audio
topic_mixer
topic_tui

Mixer README

Overview

Welcome to the audio mixer—where all the magic happens when multiple people are talking at once!

Picture yourself in a group video call. Person A is talking, Person B laughs, Person C asks a question—all happening simultaneously. Your speakers don't have three separate outputs (well, most don't). So how does your computer play all three audio streams at once? That's where the mixer comes in!

The mixer takes multiple audio streams (one from each client) and combines them into a single output stream that gets sent to everyone. It's like a real mixing board at a concert—each microphone is a separate input, and the mixer blends them into one cohesive sound that goes to the speakers.

But here's the cool part: when lots of people are talking at once, the mixer automatically applies "ducking" (volume reduction) so the combined audio doesn't clip or distort. It's like how a good sound engineer knows to turn down each microphone a bit when everyone's singing together—the mix stays clear and balanced.

Implementation: lib/mixer.h

What makes the mixer special?

  • Real-time mixing: Combines multiple audio streams on the fly
  • Dynamic source management: Sources can join or leave without disrupting the mix
  • Active speaker detection: Automatically identifies who's talking loudest
  • Automatic ducking: Attenuates background sources when someone is speaking
  • Dynamic range compression: Prevents clipping with professional compressor
  • Noise gate: Suppresses background noise below threshold with hysteresis
  • High-pass filtering: Removes low-frequency rumble and noise
  • Soft clipping: Prevents harsh digital clipping artifacts
  • Crowd scaling: Automatically adjusts volume based on participant count
  • Thread-safe: Reader-writer locks for concurrent access
  • Low latency: Fixed 256-sample frame processing
  • O(1) source exclusion: Bitset-based tracking for echo cancellation

Architecture

Mixer Design:

  • Single mixer instance per server
  • Per-client audio input buffers
  • Shared output buffer for mixed audio
  • Thread-safe operation with mutex protection

Audio Flow:

Client 1 Audio → Input Buffer 1 ──┐
Client 2 Audio → Input Buffer 2 ──┤
Client 3 Audio → Input Buffer 3 ──┼→ Mixer → Mixed Output → All Clients
... ─┘

Operations

Initialization

Create Mixer:

// mixer_create returns a pointer to a new mixer (NULL on failure)
if (!mixer) {
log_error("Failed to create mixer");
return ASCIICHAT_ERROR_MEMORY;
}
#define MIXER_MAX_SOURCES
Maximum number of simultaneous audio sources.
Definition mixer.h:105
mixer_t * mixer_create(int max_sources, int sample_rate)
Create a new audio mixer.
Definition mixer.c:225
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
For ducking, this is the live record that ties threshold_dB, leader_margin_dB, atten_dB,...
Definition mixer.h:350

Source Management

Add Audio Source (client with audio ring buffer):

uint32_t client_id = 12345;
audio_ring_buffer_t *client_audio_buffer = ...; // Client's audio ring buffer
int result = mixer_add_source(mixer, client_id, client_audio_buffer);
if (result < 0) {
log_error("Failed to add client %u to mixer", client_id);
return ASCIICHAT_ERROR_FULL;
}
log_info("Client %u added to mixer at index %d", client_id, result);
int mixer_add_source(mixer_t *mixer, const char *client_id, audio_ring_buffer_t *buffer)
Add an audio source to the mixer.
Definition mixer.c:443
unsigned int uint32_t
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
struct audio_ring_buffer audio_ring_buffer_t
Audio ring buffer for real-time audio streaming.

Remove Audio Source:

mixer_remove_source(mixer, client_id);
log_info("Client %u removed from mixer", client_id);
void mixer_remove_source(mixer_t *mixer, const char *client_id)
Remove an audio source from the mixer.
Definition mixer.c:511

Audio Processing

The mixer reads audio directly from each client's audio ring buffer. Clients write their audio samples to their ring buffer, and the mixer reads and mixes them during processing.

Mix Audio (reads from all source ring buffers):

float mixed_output[MIXER_FRAME_SIZE];
int samples_mixed = mixer_process(mixer, mixed_output, MIXER_FRAME_SIZE);
if (samples_mixed > 0) {
// Send mixed audio to all clients
send_audio_to_all_clients(mixed_output, samples_mixed);
}
#define MIXER_FRAME_SIZE
Number of samples processed per audio frame.
Definition mixer.h:116
int mixer_process(mixer_t *mixer, float *output, int num_samples)
Process audio from all active sources.
Definition mixer.c:589

Mix Audio Excluding a Source (for echo cancellation):

// Mix all sources except the client we're sending to (prevents echo)
float output_for_client[MIXER_FRAME_SIZE];
int samples = mixer_process_excluding_source(mixer, output_for_client,
MIXER_FRAME_SIZE, client_id);
send_audio_to_client(client_id, output_for_client, samples);
int mixer_process_excluding_source(mixer_t *mixer, float *output, int num_samples, uint32_t exclude_client_id)
Process audio from all sources except one (for per-client output).
Definition mixer.c:759

Cleanup

Destroy Mixer:

mixer_destroy(mixer); // Pass pointer, not address-of
void mixer_destroy(mixer_t *mixer)
Destroy a mixer and free all resources.
Definition mixer.c:411

Active Speaker Detection & Ducking

The ducking system automatically identifies who's speaking and attenuates background sources to improve clarity. This is more sophisticated than simple volume scaling.

How It Works:

  • Leader Detection: The loudest source(s) above threshold_dB are identified
  • Margin Tracking: Sources within leader_margin_dB of the loudest are also "leaders"
  • Attenuation: Non-leader sources are attenuated by atten_dB
  • Smooth Transitions: Attack/release curves prevent jarring volume changes

The ducking uses dB-based audio analysis:

// Ducking parameters (in dB and milliseconds)
typedef struct {
float threshold_dB; // Speaking threshold (-40dB typical)
float leader_margin_dB; // Margin to be considered a leader (6dB typical)
float atten_dB; // Attenuation for non-leaders (-12dB typical)
float attack_ms; // How fast ducking engages (10ms typical)
float release_ms; // How fast ducking releases (100ms typical)
Ducking system settings and state.
Definition mixer.h:290

Practical Example:

  • Person A speaks at -20dB (loud)
  • Person B speaks at -25dB (within 6dB margin of A)
  • Person C has background noise at -50dB (below threshold)
  • Result: A and B are heard at full volume, C is attenuated by 12dB

This allows multiple people to have a natural conversation while suppressing background noise from inactive participants.

Thread Safety

Reader-Writer Lock Protection:

  • Source array protected by reader-writer locks (rwlock)
  • Multiple readers can process audio concurrently
  • Writers (add/remove source) get exclusive access
  • Bitset operations are atomic for source exclusion

Thread Model:

// Network receive thread - writes to client's ring buffer
void* client_receive_thread(void *arg) {
client_t *client = (client_t *)arg;
while (running) {
float samples[256];
receive_audio_packet(client->id, samples, 256);
// Write directly to client's audio ring buffer
audio_ring_buffer_write(client->audio_buffer, samples, 256);
}
return NULL;
}
// Audio processing thread - reads from all ring buffers via mixer
void* audio_mix_thread(void *arg) {
mixer_t *mixer = (mixer_t *)arg;
while (running) {
float mixed[MIXER_FRAME_SIZE];
int samples = mixer_process(mixer, mixed, MIXER_FRAME_SIZE);
if (samples > 0) {
send_to_all_clients(mixed, samples);
}
}
return NULL;
}
asciichat_error_t audio_ring_buffer_write(audio_ring_buffer_t *rb, const float *data, int samples)
Write audio samples to ring buffer.

Performance

Mixing Algorithm:

  • Simple additive mixing with ducking
  • SIMD optimization where available
  • Minimal memory allocations
  • Cache-friendly data layout

CPU Usage:

  • 2 clients: ~1% CPU
  • 4 clients: ~2% CPU
  • 8 clients: ~3% CPU
  • 16 clients: ~5% CPU

Latency:

  • Mixing latency: <1ms
  • Total audio latency: ~50-60ms (includes network)

Buffer Management

Per-Client Buffers:

  • Fixed-size circular buffers
  • Automatic overflow handling
  • Underrun detection and handling

Buffer Configuration:

mixer.buffer_size = 8192; // Samples per client buffer
mixer.min_frames = 256; // Minimum frames for mixing

Overflow Handling:

  • Drop oldest frames when buffer full
  • Log warning message
  • Continue operation without crash

Underrun Handling:

  • Output silence when insufficient data
  • Log debug message
  • Wait for more data

Integration Example

Complete Server Integration:

// Initialize mixer
mixer_t mixer;
mixer_init(&mixer, MAX_CLIENTS);
// When client connects
void on_client_connect(uint32_t client_id) {
mixer_add_client(&mixer, client_id);
log_info("Client %u added to audio mixer", client_id);
}
// When client disconnects
void on_client_disconnect(uint32_t client_id) {
mixer_remove_client(&mixer, client_id);
log_info("Client %u removed from audio mixer", client_id);
}
// When audio packet arrives
void on_audio_packet(uint32_t client_id, float *samples, size_t num_frames) {
mixer_submit_audio(&mixer, client_id, samples, num_frames);
}
// Audio mixing thread
void* audio_thread(void *arg) {
float mixed[256];
while (running) {
size_t frames = mixer_process(&mixer, mixed, 256);
if (frames > 0) {
broadcast_audio_to_all_clients(mixed, frames);
}
usleep(5000); // ~5ms sleep for 44.1kHz
}
return NULL;
}
// Cleanup
mixer_destroy(&mixer);
#define MAX_CLIENTS
Maximum possible clients (static array size) - actual runtime limit set by –max-clients (1-128).

Best Practices

DO:

  • Enable ducking for 4+ clients
  • Monitor buffer overflows/underruns
  • Use consistent sample rates across clients
  • Remove clients from mixer on disconnect
  • Use dedicated audio mixing thread

DON'T:

  • Don't mix audio on network thread
  • Don't forget to remove disconnected clients
  • Don't use different sample rates per client
  • Don't disable ducking with many clients
  • Don't mix audio without mutex protection
See also
mixer.h
audio.h
ringbuffer.h