ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
client_pipeline.h File Reference

Unified client-side audio processing pipeline. More...

Go to the source code of this file.

Data Structures

struct  client_audio_pipeline_flags_t
 Component enable/disable flags. More...
struct  client_audio_pipeline_config_t
 Pipeline configuration parameters. More...
struct  client_audio_pipeline_t
 Client audio pipeline state. More...

Macros

#define CLIENT_AUDIO_PIPELINE_FLAGS_ALL
 Component enable/disable flags.
#define CLIENT_AUDIO_PIPELINE_FLAGS_MINIMAL
 Minimal flags for testing (only codec, no processing).

Typedefs

typedef struct SpeexPreprocessState_ SpeexPreprocessState
typedef struct JitterBuffer_ JitterBuffer
typedef struct webrtc_EchoCanceller3 webrtc_EchoCanceller3
typedef struct OpusEncoder OpusEncoder
typedef struct OpusDecoder OpusDecoder

Functions

client_audio_pipeline_config_t client_audio_pipeline_default_config (void)
 Audio-pipeline setup for channel conversion, Opus encoding, echo handling, and preprocessing. The channel counts, sample rate, frame duration, bitrate, and processor settings are copied into the pipeline during initialization; the config itself can then be stack-owned.
client_audio_pipeline_config_t client_audio_pipeline_config_for_source (bool has_media_audio)
Lifecycle Functions

When code needs to work with client audio pipeline, it keeps flags, echo_canceller, processor, preprocess here instead of scattering it across globals. Initialization establishes the handles and sizes; teardown must release any allocation, lock, thread, or callback context recorded in those fields.

client_audio_pipeline_t * client_audio_pipeline_create (const client_audio_pipeline_config_t *config)
 Create a new client audio pipeline.
void client_audio_pipeline_destroy (client_audio_pipeline_t *pipeline)
 Destroy a client audio pipeline.
Flag Management
void client_audio_pipeline_set_flags (client_audio_pipeline_t *pipeline, client_audio_pipeline_flags_t flags)
 Set component enable flags.
client_audio_pipeline_flags_t client_audio_pipeline_get_flags (client_audio_pipeline_t *pipeline)
 Get current component enable flags.
Capture Path (Microphone → Network)
int client_audio_pipeline_capture (client_audio_pipeline_t *pipeline, const float *input, int num_samples, uint8_t *opus_out, int opus_out_size)
 Process captured audio and encode to Opus.
Playback Path (Network → Speakers)
int client_audio_pipeline_playback (client_audio_pipeline_t *pipeline, const uint8_t *opus_in, int opus_len, float *output, int max_samples)
 Decode Opus packet and process for playback.
int client_audio_pipeline_get_playback_frame (client_audio_pipeline_t *pipeline, float *output, int num_samples)
 Get audio frame from jitter buffer for playback callback.
Full-Duplex AEC3 Processing
void client_audio_pipeline_process_duplex (client_audio_pipeline_t *pipeline, const float *render_samples, int render_count, const float *capture_samples, int capture_count, float *processed_output)
 Process AEC3 inline in full-duplex callback.
Status and Diagnostics
int client_audio_pipeline_jitter_margin (client_audio_pipeline_t *pipeline)
 Get jitter buffer margin (buffered time in ms).
bool client_audio_pipeline_voice_detected (client_audio_pipeline_t *pipeline)
 Check if VAD detected voice activity in last capture.
void client_audio_pipeline_reset (client_audio_pipeline_t *pipeline)
 Reset pipeline state.

Detailed Description

Unified client-side audio processing pipeline.

This header provides a complete audio processing pipeline for ascii-chat clients, integrating WebRTC AEC3 (production-grade echo cancellation), SpeexDSP (noise suppression, AGC, VAD), Speex jitter buffer, Opus codec, and mixer components (compression, noise gate, filters).

PIPELINE ARCHITECTURE:

CAPTURE PATH (microphone → network): Mic Input (float32, 48kHz) ↓ Echo Cancellation (WebRTC AEC3 - automatic network delay estimation + adaptive filtering) ↓ Preprocessor (Noise/AGC/VAD) ↓ High-Pass Filter (remove rumble) ↓ Low-Pass Filter (remove hiss) ↓ Noise Gate (silence detection) ↓ Compressor (dynamic range control) ↓ Opus Encode → Network

PLAYBACK PATH (network → speakers): Network ↓ Speex Jitter Buffer ↓ Opus Decode ↓ Register with AEC (WebRTC AEC3 reference signal for echo learning) ↓ Soft Clipping → Speakers

COMPONENT FLAGS:

Each processing stage can be individually enabled/disabled via flags. This allows testing and debugging specific components.

THREAD SAFETY:

  • Pipeline has internal mutex for state protection
  • Capture and playback paths can run concurrently
  • Echo reference feeding is thread-safe
Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
December 2025

Definition in file client_pipeline.h.

Macro Definition Documentation

◆ CLIENT_AUDIO_PIPELINE_FLAGS_ALL

#define CLIENT_AUDIO_PIPELINE_FLAGS_ALL
Value:
.echo_cancel = true, \
.noise_suppress = true, \
.agc = true, \
.vad = true, \
.jitter_buffer = true, \
.compressor = true, \
.noise_gate = true, \
.highpass = true, \
.lowpass = true, \
})
Component enable/disable flags.

Component enable/disable flags.

Default flags with all processing enabled

Definition at line 111 of file client_pipeline.h.

111#define CLIENT_AUDIO_PIPELINE_FLAGS_ALL \
112 ((client_audio_pipeline_flags_t){ \
113 .echo_cancel = true, \
114 .noise_suppress = true, \
115 .agc = true, \
116 .vad = true, \
117 .jitter_buffer = true, \
118 .compressor = true, \
119 .noise_gate = true, \
120 .highpass = true, \
121 .lowpass = true, \
122 })

◆ CLIENT_AUDIO_PIPELINE_FLAGS_MINIMAL

#define CLIENT_AUDIO_PIPELINE_FLAGS_MINIMAL
Value:
.echo_cancel = false, \
.noise_suppress = false, \
.agc = false, \
.vad = false, \
.jitter_buffer = false, \
.compressor = false, \
.noise_gate = false, \
.highpass = false, \
.lowpass = false, \
})

Minimal flags for testing (only codec, no processing).

Definition at line 127 of file client_pipeline.h.

127#define CLIENT_AUDIO_PIPELINE_FLAGS_MINIMAL \
128 ((client_audio_pipeline_flags_t){ \
129 .echo_cancel = false, \
130 .noise_suppress = false, \
131 .agc = false, \
132 .vad = false, \
133 .jitter_buffer = false, \
134 .compressor = false, \
135 .noise_gate = false, \
136 .highpass = false, \
137 .lowpass = false, \
138 })

Typedef Documentation

◆ JitterBuffer

typedef struct JitterBuffer_ JitterBuffer

Definition at line 67 of file client_pipeline.h.

◆ SpeexPreprocessState

typedef struct SpeexPreprocessState_ SpeexPreprocessState

Definition at line 66 of file client_pipeline.h.

◆ webrtc_EchoCanceller3

Definition at line 70 of file client_pipeline.h.

Function Documentation

◆ client_audio_pipeline_capture()

int client_audio_pipeline_capture ( client_audio_pipeline_t * pipeline,
const float * input,
int num_samples,
uint8_t * opus_out,
int max_opus_len )

Process captured audio and encode to Opus.

Parameters
pipelinePipeline instance
inputInput samples (float32, -1.0 to 1.0)
num_samplesNumber of input samples (should match frame_size)
opus_outOutput buffer for Opus packet
opus_out_sizeSize of opus_out buffer (should be >= MAX_OPUS_PACKET)
Returns
Number of bytes written to opus_out, or negative on error

Processing pipeline (when flags enabled):

  1. Convert float → int16
  2. Echo cancellation (subtract speaker output from mic input)
  3. Speex preprocessor (noise suppression, AGC, VAD)
  4. Convert int16 → float
  5. High-pass filter
  6. Low-pass filter
  7. Noise gate
  8. Compressor
  9. Opus encode

Encode already-processed audio to Opus.

In full-duplex mode, AEC3 and DSP processing are done in process_duplex(). This function just does Opus encoding.

Definition at line 480 of file client_pipeline.cpp.

482 {
483 if (!pipeline || !input || !opus_out || num_samples != pipeline->frame_size) {
484 return -1;
485 }
486
487 // Input is already processed by process_duplex() in full-duplex mode.
488 // Just encode with Opus.
490 const float *pcm = input;
491 const int frames = num_samples / pipeline->config.channels;
492 if (pipeline->config.encoder_channels != pipeline->config.channels) {
493 if (frames > (int)(sizeof(converted) / sizeof(converted[0])) /
494 pipeline->config.encoder_channels)
495 return -1;
496 if (audio_convert_channels(input, (size_t)frames, pipeline->config.channels,
497 converted, pipeline->config.encoder_channels) !=
499 return -1;
500 pcm = converted;
501 }
502 int opus_len =
503 opus_encode_float(pipeline->encoder, pcm, frames, opus_out, max_opus_len);
504
505 if (opus_len < 0) {
506 log_error_every(US_PER_SEC_INT, "Opus encoding failed: %d", opus_len);
507 return -1;
508 }
509
510 return opus_len;
511}
asciichat_error_t audio_convert_channels(const float *input, size_t frames, unsigned input_channels, float *output, unsigned output_channels)
#define AUDIO_OPUS_MAX_DECODE_SAMPLES
#define AUDIO_CHANNELS
@ ASCIICHAT_OK
Definition error_codes.h:50
#define US_PER_SEC_INT
Definition time.h:177
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
int encoder_channels
Transmitted channels, independent of playback.
int channels
PCM channels (1 or 2).
client_audio_pipeline_config_t config

References ASCIICHAT_OK, AUDIO_CHANNELS, audio_convert_channels(), AUDIO_OPUS_MAX_DECODE_SAMPLES, client_audio_pipeline_config_t::channels, client_audio_pipeline_t::config, client_audio_pipeline_t::encoder, client_audio_pipeline_config_t::encoder_channels, ERROR_NOT_SUPPORTED, client_audio_pipeline_t::frame_size, log_error_every, SET_ERRNO, and US_PER_SEC_INT.

◆ client_audio_pipeline_config_for_source()

client_audio_pipeline_config_t client_audio_pipeline_config_for_source ( bool has_media_audio)

Select the codec profile using current capture options and actual media audio availability.

Definition at line 139 of file client_pipeline.cpp.

139 {
142 config.channels = AUDIO_CHANNELS;
143 const options_t *options = options_get();
144 if (options) {
146 options->audio_spectral && !options->test_audio;
148 options->reduce_noise && !options->test_audio;
149 config.processor.spectral.fft_size = options->audio_fft_size;
155 bool media = options->test_audio ||
156 (has_media_audio &&
159 bool stereo_microphone = options->microphone_channels == 2;
160 config.opus_application = media || stereo_microphone
163 config.opus_bitrate = media || stereo_microphone ? 128000 : 32000;
164 }
165 return config;
166}
client_audio_pipeline_config_t client_audio_pipeline_default_config(void)
Audio-pipeline setup for channel conversion, Opus encoding, echo handling, and preprocessing....
@ OPUS_APPLICATION_AUDIO
General audio (optimized for music).
Definition opus.h:93
@ OPUS_APPLICATION_VOIP
Voice over IP (optimized for speech).
Definition opus.h:92
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:513
@ AUDIO_CAPTURE_SOURCE_REMOTE
Definition options.h:291
@ AUDIO_CAPTURE_SOURCE_MIC
Definition options.h:291
spectral_config_t spectral
Definition processor.h:37
Pipeline configuration parameters.
audio_processor_config_t processor
bool audio_spectral_agc
Definition options.h:1105
audio_capture_source_t audio_capture_source
Local capture/media selection policy.
Definition options.h:1115
bool audio_spectral_gate
Definition options.h:1108
bool audio_adaptive_eq
Definition options.h:1111
bool test_audio
Replace microphone capture with a repeating audible test signal.
Definition options.h:1104
int microphone_channels
Selected microphone channels: 1 (speech) or 2 (stereo).
Definition options.h:1119
bool audio_pitch_correct
Definition options.h:1103
bool audio_multiband
Definition options.h:1110
int audio_fft_size
Definition options.h:1112
bool audio_spectral
Definition options.h:1106
bool reduce_noise
Apply neural microphone noise reduction in client-like modes.
Definition options.h:1109

References spectral_config_t::adaptive_eq, options_state::audio_adaptive_eq, options_state::audio_capture_source, AUDIO_CAPTURE_SOURCE_MIC, AUDIO_CAPTURE_SOURCE_REMOTE, AUDIO_CHANNELS, options_state::audio_fft_size, options_state::audio_multiband, options_state::audio_pitch_correct, options_state::audio_spectral, options_state::audio_spectral_agc, options_state::audio_spectral_gate, spectral_config_t::auto_gain, client_audio_pipeline_config_t::channels, client_audio_pipeline_default_config(), spectral_config_t::compressor, spectral_config_t::fft_size, options_state::microphone_channels, spectral_config_t::noise_gate, options_get(), client_audio_pipeline_config_t::opus_application, OPUS_APPLICATION_AUDIO, OPUS_APPLICATION_VOIP, client_audio_pipeline_config_t::opus_bitrate, spectral_config_t::pitch_correct, client_audio_pipeline_config_t::processor, options_state::reduce_noise, audio_processor_config_t::rnnoise_enabled, audio_processor_config_t::spectral, audio_processor_config_t::spectral_enabled, and options_state::test_audio.

Referenced by audio_connection_init(), session_audio_start_duplex(), and session_participant_start_audio().

◆ client_audio_pipeline_create()

client_audio_pipeline_t * client_audio_pipeline_create ( const client_audio_pipeline_config_t * config)

Create a new client audio pipeline.

Parameters
configPipeline configuration (NULL for defaults)
Returns
New pipeline instance, or NULL on failure

Allocates and initializes all audio processing components. Must be destroyed with client_audio_pipeline_destroy().

Create a new client audio pipeline.

This function:

  • Allocates the pipeline structure
  • Initializes Opus encoder/decoder
  • Sets up WebRTC AEC3 echo cancellation
  • Configures all audio processing parameters

Definition at line 182 of file client_pipeline.cpp.

182 {
185 if (!p) {
186 log_error("Failed to allocate client audio pipeline");
187 return NULL;
188 }
189
190 // Use default config if none provided
191 if (config) {
192 p->config = *config;
193 } else {
195 }
196
197 if (p->config.channels == 0)
199 if (p->config.encoder_channels == 0)
201 if ((p->config.channels != 1 && p->config.channels != 2) ||
202 (p->config.encoder_channels != 1 && p->config.encoder_channels != 2)) {
203 SAFE_FREE(p);
204 return NULL;
205 }
206 p->flags = p->config.flags;
207 p->frame_size =
208 static_cast<int>(p->config.sample_rate * p->config.frame_duration_ms /
209 1000 * p->config.channels);
210
211 // No mutex needed - full-duplex means single callback thread handles all AEC3
212
213 // Initialize Opus encoder/decoder first (no exceptions)
214 int opus_error = 0;
215 p->encoder =
216 opus_encoder_create(p->config.sample_rate, p->config.encoder_channels,
217 p->config.opus_application, &opus_error);
218 if (!p->encoder || opus_error != OPUS_OK) {
219 log_error("Failed to create Opus encoder: %d", opus_error);
220 goto error;
221 }
224 goto error;
225
226 // Create Opus decoder
227 p->decoder = opus_decoder_create(p->config.sample_rate, p->config.channels,
228 &opus_error);
229 if (!p->decoder || opus_error != OPUS_OK) {
230 log_error("Failed to create Opus decoder: %d", opus_error);
231 goto error;
232 }
233
234 // Create WebRTC AEC3 Echo Cancellation
235 // AEC3 provides production-grade acoustic echo cancellation with:
236 // - Automatic network delay estimation (0-500ms)
237 // - Adaptive filtering to actual echo path
238 // - Residual echo suppression via spectral subtraction
239 // - Jitter buffer handling via side information
240 if (p->flags.echo_cancel) {
241 // Configure AEC3 for better low-frequency (bass) echo cancellation
242 webrtc::EchoCanceller3Config aec3_config;
243
244 // Increase filter length for bass frequencies (default 13 blocks = ~17ms)
245 // Bass at 80Hz has 12.5ms period, so we need at least 50+ blocks (~67ms)
246 // to properly model the echo path for low frequencies
247 aec3_config.filter.main.length_blocks = 50; // ~67ms (was 13)
248 aec3_config.filter.shadow.length_blocks = 50; // ~67ms (was 13)
249 aec3_config.filter.main_initial.length_blocks = 25; // ~33ms (was 12)
250 aec3_config.filter.shadow_initial.length_blocks = 25; // ~33ms (was 12)
251
252 // More aggressive low-frequency suppression thresholds
253 // Lower values = more aggressive echo suppression
254 aec3_config.echo_audibility.audibility_threshold_lf = 5; // (was 10)
255
256 // Create AEC3 using the factory
257 auto factory = webrtc::EchoCanceller3Factory(aec3_config);
258
259 std::unique_ptr<webrtc::EchoControl> echo_control =
260 factory.Create(static_cast<int>(p->config.sample_rate), // 48kHz
261 p->config.channels, // speaker channels
262 p->config.channels // microphone channels
263 );
264
265 if (!echo_control) {
266 log_warn("Failed to create WebRTC AEC3 instance - echo cancellation "
267 "unavailable");
268 p->echo_canceller = NULL;
269 } else {
270 // Successfully created AEC3 - wrap in our C++ wrapper for C compatibility
271 auto wrapper = new WebRTCAec3Wrapper();
272 wrapper->aec3 = std::move(echo_control);
273 wrapper->config = aec3_config;
274 p->echo_canceller = wrapper;
275
276 log_info(
277 "✓ WebRTC AEC3 initialized (67ms filter for bass, adaptive delay)");
278
279 // Create persistent AudioBuffer instances for AEC3
280 p->aec3_render_buffer = new webrtc::AudioBuffer(
281 48000, p->config.channels, 48000, p->config.channels, 48000,
282 p->config.channels);
283 p->aec3_capture_buffer = new webrtc::AudioBuffer(
284 48000, p->config.channels, 48000, p->config.channels, 48000,
285 p->config.channels);
286
287 auto *render_buf =
288 static_cast<webrtc::AudioBuffer *>(p->aec3_render_buffer);
289 auto *capture_buf =
290 static_cast<webrtc::AudioBuffer *>(p->aec3_capture_buffer);
291
292 // Zero-initialize channel data
293 float *const *render_ch = render_buf->channels();
294 float *const *capture_ch = capture_buf->channels();
295 for (int channel = 0; channel < p->config.channels; channel++) {
296 if (render_ch && render_ch[channel])
297 memset(render_ch[channel], 0, 480 * sizeof(float));
298 if (capture_ch && capture_ch[channel])
299 memset(capture_ch[channel], 0, 480 * sizeof(float));
300 }
301
302 // Prime filterbank state with dummy processing cycle
303 render_buf->SplitIntoFrequencyBands();
304 render_buf->MergeFrequencyBands();
305 capture_buf->SplitIntoFrequencyBands();
306 capture_buf->MergeFrequencyBands();
307
308 log_debug(" - AudioBuffer filterbank state initialized");
309
310 // Warm up AEC3 with 10 silent frames to initialize internal state
311 for (int warmup = 0; warmup < 10; warmup++) {
312 for (int channel = 0; channel < p->config.channels; channel++) {
313 memset(render_ch[channel], 0, 480 * sizeof(float));
314 memset(capture_ch[channel], 0, 480 * sizeof(float));
315 }
316
317 render_buf->SplitIntoFrequencyBands();
318 wrapper->aec3->AnalyzeRender(render_buf);
319 render_buf->MergeFrequencyBands();
320
321 wrapper->aec3->AnalyzeCapture(capture_buf);
322 capture_buf->SplitIntoFrequencyBands();
323 wrapper->aec3->SetAudioBufferDelay(0);
324 wrapper->aec3->ProcessCapture(capture_buf, false);
325 capture_buf->MergeFrequencyBands();
326 }
327 log_debug(" - AEC3 warmed up with 10 silent frames");
328 log_debug(" - Persistent AudioBuffer instances created");
329 }
330 }
331
332 // Initialize debug WAV writers for AEC3 analysis (if echo_cancel enabled)
333 p->debug_wav_aec3_in = NULL;
334 p->debug_wav_aec3_out = NULL;
335 if (p->flags.echo_cancel && wav_dump_enabled()) {
336 // Record microphone diagnostics only when WAV dumping was requested.
337 char tmp[PLATFORM_MAX_PATH_LENGTH];
338 if (platform_get_temp_dir(tmp, sizeof(tmp))) {
339 char path[PLATFORM_MAX_PATH_LENGTH];
340 safe_snprintf(path, sizeof(path), "%s/aec3_input.wav", tmp);
341 p->debug_wav_aec3_in = wav_writer_open(path, 48000, p->config.channels);
342 safe_snprintf(path, sizeof(path), "%s/aec3_output.wav", tmp);
344 }
345 if (p->debug_wav_aec3_in) {
346 log_info("Debug: Recording AEC3 input WAV to temp dir");
347 }
348 if (p->debug_wav_aec3_out) {
349 log_info("Debug: Recording AEC3 output WAV to temp dir");
350 }
351
352 log_info("✓ AEC3 echo cancellation enabled (full-duplex mode, no ring "
353 "buffer delay)");
354 }
355
366 goto error;
367 p->initialized = true;
368
369 // Initialize startup fade-in to prevent initial microphone click
370 // 200ms at 48kHz = 9600 samples - gradual ramp from silence to full volume
371 // Longer fade-in (200ms vs 50ms) gives much smoother transition without
372 // audible pop
373 p->capture_fadein_remaining = (p->config.sample_rate * 200) / 1000 *
374 p->config.channels; // 200ms worth of samples
375 log_debug("✓ Capture fade-in: %d samples (200ms)",
377
378 log_info("Audio pipeline created: %dHz, %llums frames, %dkbps Opus",
380 (unsigned long long)p->config.frame_duration_ms,
381 p->config.opus_bitrate / 1000);
382
383 (void)NAMED_REGISTER_CLIENT_AUDIO_PIPELINE(p, "audio_pipeline", NULL);
384
385 return p;
386
387error:
389 return NULL;
390}
void client_audio_pipeline_destroy(client_audio_pipeline_t *pipeline)
Destroy a client audio pipeline.
asciichat_error_t audio_opus_configure_encoder(OpusEncoder *encoder, int bitrate)
Definition opus.c:22
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
#define NAMED_REGISTER_CLIENT_AUDIO_PIPELINE(pipeline, name, parent_ptr)
Register a client audio pipeline with automatic format specifier.
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
asciichat_error_t audio_processor_create(const audio_processor_config_t *c, audio_processor_t **out)
Definition processor.c:95
C++ wrapper for WebRTC AEC3 (opaque to C code).
int channels
Interleaved PCM channels; zero retains the mono API default.
Definition processor.h:31
audio_processor_flags_t flags
Definition processor.h:33
client_audio_pipeline_flags_t flags
Client audio pipeline state.
audio_processor_t * processor
client_audio_pipeline_flags_t flags
bool platform_get_temp_dir(char *temp_dir, size_t path_size)
Definition util.c:81
bool wav_dump_enabled(void)
Check if audio dumping is enabled via environment.
Definition wav_writer.c:153
wav_writer_t * wav_writer_open(const char *filepath, int sample_rate, int channels)
Open WAV file for writing.
Definition wav_writer.c:59

References client_audio_pipeline_t::aec3_capture_buffer, client_audio_pipeline_t::aec3_render_buffer, audio_processor_flags_t::agc, client_audio_pipeline_flags_t::agc, ASCIICHAT_OK, AUDIO_CHANNELS, audio_opus_configure_encoder(), audio_processor_create(), client_audio_pipeline_t::capture_fadein_remaining, audio_processor_config_t::channels, client_audio_pipeline_config_t::channels, client_audio_pipeline_default_config(), client_audio_pipeline_destroy(), audio_processor_flags_t::compressor, client_audio_pipeline_flags_t::compressor, client_audio_pipeline_t::config, client_audio_pipeline_t::debug_wav_aec3_in, client_audio_pipeline_t::debug_wav_aec3_out, client_audio_pipeline_t::decoder, client_audio_pipeline_flags_t::echo_cancel, client_audio_pipeline_t::echo_canceller, client_audio_pipeline_t::encoder, client_audio_pipeline_config_t::encoder_channels, ERROR_NOT_SUPPORTED, audio_processor_config_t::flags, client_audio_pipeline_config_t::flags, client_audio_pipeline_t::flags, client_audio_pipeline_config_t::frame_duration_ms, client_audio_pipeline_t::frame_size, audio_processor_flags_t::highpass, client_audio_pipeline_flags_t::highpass, client_audio_pipeline_t::initialized, log_debug, log_error, log_info, log_warn, audio_processor_flags_t::lowpass, client_audio_pipeline_flags_t::lowpass, NAMED_REGISTER_CLIENT_AUDIO_PIPELINE, audio_processor_flags_t::noise_gate, client_audio_pipeline_flags_t::noise_gate, client_audio_pipeline_config_t::opus_application, client_audio_pipeline_config_t::opus_bitrate, platform_get_temp_dir(), client_audio_pipeline_config_t::processor, client_audio_pipeline_t::processor, SAFE_CALLOC, SAFE_FREE, audio_processor_config_t::sample_rate, client_audio_pipeline_config_t::sample_rate, spectral_config_t::sample_rate, SET_ERRNO, audio_processor_config_t::spectral, wav_dump_enabled(), and wav_writer_open().

Referenced by audio_connection_init(), and session_audio_start_duplex().

◆ client_audio_pipeline_default_config()

client_audio_pipeline_config_t client_audio_pipeline_default_config ( void )

Audio-pipeline setup for channel conversion, Opus encoding, echo handling, and preprocessing. The channel counts, sample rate, frame duration, bitrate, and processor settings are copied into the pipeline during initialization; the config itself can then be stack-owned.

Get default configuration

Returns
Configuration with sensible defaults for voice chat

Definition at line 120 of file client_pipeline.cpp.

120 {
122 .channels = AUDIO_CHANNELS,
123 .encoder_channels = AUDIO_CHANNELS,
124 .sample_rate = AUDIO_SAMPLE_RATE,
125 .frame_duration_ms = CLIENT_AUDIO_PIPELINE_FRAME_MS,
126 .opus_bitrate = 32000,
127 .opus_application = OPUS_APPLICATION_VOIP,
128
129 .echo_filter_ms = 250,
130
132 .jitter_margin_ms = 60,
133
134 .flags = {true, true, true, true, true, true, true, true, true},
135 };
136}
#define CLIENT_AUDIO_PIPELINE_FRAME_MS
#define AUDIO_SAMPLE_RATE
Definition audio/limits.h:9
audio_processor_config_t audio_processor_default_config(int sample_rate)
Definition processor.c:39

References AUDIO_CHANNELS, audio_processor_default_config(), AUDIO_SAMPLE_RATE, CLIENT_AUDIO_PIPELINE_FRAME_MS, audio_processor_config_t::flags, and OPUS_APPLICATION_VOIP.

Referenced by client_audio_pipeline_config_for_source(), and client_audio_pipeline_create().

◆ client_audio_pipeline_destroy()

void client_audio_pipeline_destroy ( client_audio_pipeline_t * pipeline)

Destroy a client audio pipeline.

Parameters
pipelinePipeline to destroy (can be NULL)

Frees all resources including SpeexDSP states, Opus codec, and all work buffers.

Definition at line 392 of file client_pipeline.cpp.

392 {
393 if (!pipeline)
394 return;
395
397 pipeline->processor = NULL;
398
399 // Clean up WebRTC AEC3 AudioBuffer instances
400 if (pipeline->aec3_render_buffer) {
401 delete static_cast<webrtc::AudioBuffer *>(pipeline->aec3_render_buffer);
402 pipeline->aec3_render_buffer = NULL;
403 }
404 if (pipeline->aec3_capture_buffer) {
405 delete static_cast<webrtc::AudioBuffer *>(pipeline->aec3_capture_buffer);
406 pipeline->aec3_capture_buffer = NULL;
407 }
408
409 // Clean up WebRTC AEC3
410 if (pipeline->echo_canceller) {
411 delete static_cast<WebRTCAec3Wrapper *>(pipeline->echo_canceller);
412 pipeline->echo_canceller = NULL;
413 }
414
415 // Clean up Opus
416 if (pipeline->encoder) {
417 opus_encoder_destroy(pipeline->encoder);
418 pipeline->encoder = NULL;
419 }
420 if (pipeline->decoder) {
421 opus_decoder_destroy(pipeline->decoder);
422 pipeline->decoder = NULL;
423 }
424
425 // Clean up debug WAV writers
426 if (pipeline->debug_wav_aec3_in) {
428 pipeline->debug_wav_aec3_in = NULL;
429 }
430 if (pipeline->debug_wav_aec3_out) {
432 pipeline->debug_wav_aec3_out = NULL;
433 }
434
435 NAMED_UNREGISTER(pipeline);
436
437 SAFE_FREE(pipeline);
438}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
void audio_processor_destroy(audio_processor_t *p)
Definition processor.c:333
File handle and sample counters needed to finalize a WAV recording.
Definition wav_writer.h:28
void wav_writer_close(wav_writer_t *writer)
Close WAV file and finalize header.
Definition wav_writer.c:127

References client_audio_pipeline_t::aec3_capture_buffer, client_audio_pipeline_t::aec3_render_buffer, audio_processor_destroy(), client_audio_pipeline_t::debug_wav_aec3_in, client_audio_pipeline_t::debug_wav_aec3_out, client_audio_pipeline_t::decoder, client_audio_pipeline_t::echo_canceller, client_audio_pipeline_t::encoder, NAMED_UNREGISTER, client_audio_pipeline_t::processor, SAFE_FREE, and wav_writer_close().

Referenced by client_audio_pipeline_create(), session_audio_destroy(), and session_audio_set_capture_source().

◆ client_audio_pipeline_get_flags()

client_audio_pipeline_flags_t client_audio_pipeline_get_flags ( client_audio_pipeline_t * pipeline)

Get current component enable flags.

Parameters
pipelinePipeline instance
Returns
Current flags

Definition at line 460 of file client_pipeline.cpp.

460 {
461 if (!pipeline) {
462 client_audio_pipeline_flags_t minimal = {false, false, false, false, false,
463 false, false, false, false};
464 return minimal;
465 }
466 // No mutex needed - flags are only written from main thread during setup
467 return pipeline->flags;
468}

References client_audio_pipeline_t::flags.

◆ client_audio_pipeline_get_playback_frame()

int client_audio_pipeline_get_playback_frame ( client_audio_pipeline_t * pipeline,
float * output,
int num_samples )

Get audio frame from jitter buffer for playback callback.

Parameters
pipelinePipeline instance
outputOutput buffer for decoded samples (float32)
num_samplesNumber of samples to retrieve
Returns
Number of samples written, or negative on error

This is called from the audio output callback to get the next frame of audio. It pulls from the jitter buffer and decodes.

Get a processed playback frame (currently just returns decoded frame)

Definition at line 550 of file client_pipeline.cpp.

551 {
552 if (!pipeline || !output) {
553 return -1;
554 }
555
556 // No mutex needed - this is a placeholder
557 memset(output, 0, num_samples * sizeof(float));
558 return num_samples;
559}

◆ client_audio_pipeline_jitter_margin()

int client_audio_pipeline_jitter_margin ( client_audio_pipeline_t * pipeline)

Get jitter buffer margin (buffered time in ms).

Parameters
pipelinePipeline instance
Returns
Current jitter buffer margin in milliseconds

Get jitter buffer margin

Definition at line 734 of file client_pipeline.cpp.

734 {
735 if (!pipeline)
736 return 0;
737 return pipeline->config.jitter_margin_ms > static_cast<uint64_t>(INT_MAX)
738 ? INT_MAX
739 : static_cast<int>(pipeline->config.jitter_margin_ms);
740}
unsigned long long uint64_t

References client_audio_pipeline_t::config, and client_audio_pipeline_config_t::jitter_margin_ms.

◆ client_audio_pipeline_playback()

int client_audio_pipeline_playback ( client_audio_pipeline_t * pipeline,
const uint8_t * opus_in,
int opus_len,
float * output,
int num_samples )

Decode Opus packet and process for playback.

Parameters
pipelinePipeline instance
opus_inOpus packet data (can be NULL for packet loss concealment)
opus_lenOpus packet length (0 if opus_in is NULL)
outputOutput buffer for decoded samples (float32)
max_samplesMaximum samples to write to output
Returns
Number of samples written to output, or negative on error

Processing pipeline (when flags enabled):

  1. Put Opus packet into jitter buffer
  2. Get packet from jitter buffer (handles reordering, loss)
  3. Opus decode
  4. Soft clipping

Note: Output should be fed to speakers AND to echo reference via client_audio_pipeline_feed_echo_ref().

Process network playback (decode and register with echo canceller as reference)

Definition at line 517 of file client_pipeline.cpp.

519 {
520 if (!pipeline || !output || num_samples <= 0 || opus_len < 0 ||
521 (!opus_in && opus_len != 0)) {
522 return -1;
523 }
524
525 // No mutex needed - Opus decoder is only used from this thread
526
527 // Decode Opus
528 int decoded_samples =
529 opus_decode_float(pipeline->decoder, opus_in, opus_len, output,
530 num_samples / pipeline->config.channels, 0);
531
532 if (decoded_samples < 0) {
533 log_error_every(US_PER_SEC_INT, "Opus decoding failed: %d",
534 decoded_samples);
535 return -1;
536 }
537
538 // Received streams can contain quiet media; microphone gating belongs at
539 // capture.
540
541 // NOTE: Render signal is queued to AEC3 in output_callback() when audio
542 // plays, not here. The capture thread drains the queue and processes AEC3.
543
544 return decoded_samples * pipeline->config.channels;
545}

References client_audio_pipeline_config_t::channels, client_audio_pipeline_t::config, client_audio_pipeline_t::decoder, ERROR_NOT_SUPPORTED, log_error_every, SET_ERRNO, and US_PER_SEC_INT.

Referenced by audio_decode_opus().

◆ client_audio_pipeline_process_duplex()

void client_audio_pipeline_process_duplex ( client_audio_pipeline_t * pipeline,
const float * render_samples,
int render_count,
const float * capture_samples,
int capture_count,
float * processed_output )

Process AEC3 inline in full-duplex callback.

Parameters
pipelinePipeline instance
render_samplesAudio samples being played to speakers RIGHT NOW
render_countNumber of render samples
capture_samplesAudio samples from microphone RIGHT NOW
capture_countNumber of capture samples
processed_outputOutput buffer for processed capture (must be capture_count size)

Called from PortAudio's single full-duplex callback where render and capture happen at the EXACT same instant. No ring buffers, no timing mismatch.

Processing:

  1. AEC3 AnalyzeRender on render_samples
  2. AEC3 AnalyzeCapture + ProcessCapture on capture_samples
  3. Apply highpass, lowpass, noise gate, compressor

REAL-TIME SAFE: No mutexes, no allocations, no blocking.

Process AEC3 inline in full-duplex callback (REAL-TIME SAFE).

This is the PROFESSIONAL approach to AEC3 timing:

  • Called from a single PortAudio full-duplex callback
  • render_samples = what is being played to speakers RIGHT NOW
  • capture_samples = what microphone captured RIGHT NOW
  • Perfect synchronization - no timing mismatch possible

This function does ALL AEC3 processing inline:

  1. AnalyzeRender on render samples (speaker output)
  2. AnalyzeCapture + ProcessCapture on capture samples
  3. Apply filters, noise gate, compressor

Returns processed capture samples in processed_output. Opus encoding is done separately by the encoding thread.

Definition at line 578 of file client_pipeline.cpp.

583 {
584 if (!pipeline || !processed_output || capture_count < 0 || render_count < 0 ||
585 capture_count % pipeline->config.channels ||
586 render_count % pipeline->config.channels)
587 return;
588
589 // Copy capture samples to output buffer for processing
590 if (capture_samples && capture_count > 0) {
591 memcpy(processed_output, capture_samples, capture_count * sizeof(float));
592 } else {
593 memset(processed_output, 0, capture_count * sizeof(float));
594 return;
595 }
596
597 // Check for AEC3 bypass
598 static int bypass_aec3 = -1;
599 if (bypass_aec3 == -1) {
600 const char *env = platform_getenv("BYPASS_AEC3");
601 bypass_aec3 =
602 (env && (strcmp(env, "1") == 0 || strcmp(env, "true") == 0)) ? 1 : 0;
603 if (bypass_aec3) {
604 log_warn("AEC3 BYPASSED (full-duplex mode) via BYPASS_AEC3=1");
605 }
606 }
607
608 // Debug WAV recording
609 if (pipeline->debug_wav_aec3_in) {
611 capture_samples, capture_count);
612 }
613
614 // Apply startup fade-in using smoothstep curve
615 if (pipeline->capture_fadein_remaining > 0) {
616 const int total_fadein_samples =
617 (pipeline->config.sample_rate * 200) / 1000 * pipeline->config.channels;
618 for (int i = 0; i < capture_count && pipeline->capture_fadein_remaining > 0;
619 i += pipeline->config.channels) {
620 float progress = 1.0f - ((float)pipeline->capture_fadein_remaining /
621 (float)total_fadein_samples);
622 float gain = smoothstep(progress);
623 for (int channel = 0; channel < pipeline->config.channels; channel++)
624 processed_output[i + channel] *= gain;
625 pipeline->capture_fadein_remaining -= pipeline->config.channels;
626 }
627 }
628
629 // WebRTC AEC3 processing - INLINE, no ring buffer, no mutex
630 if (!bypass_aec3 && pipeline->flags.echo_cancel && pipeline->echo_canceller) {
631 auto wrapper = static_cast<WebRTCAec3Wrapper *>(pipeline->echo_canceller);
632 if (wrapper && wrapper->aec3) {
633 const int channels = pipeline->config.channels;
634 const int webrtc_frame_size = 480 * channels; // 10ms of interleaved PCM
635
636 auto *render_buf =
637 static_cast<webrtc::AudioBuffer *>(pipeline->aec3_render_buffer);
638 auto *capture_buf =
639 static_cast<webrtc::AudioBuffer *>(pipeline->aec3_capture_buffer);
640
641 if (render_buf && capture_buf) {
642 float *const *render_channels = render_buf->channels();
643 float *const *capture_channels = capture_buf->channels();
644
645 if (render_channels && render_channels[0] && capture_channels &&
646 capture_channels[0]) {
647 // Verify render_samples is valid before accessing
648 if (!render_samples && render_count > 0) {
649 log_warn_every(1000000,
650 "AEC3: render_samples is NULL but render_count=%d",
651 render_count);
652 return;
653 }
654
655 // Process in 10ms chunks (AEC3 requirement)
656 int render_offset = 0;
657 int capture_offset = 0;
658
659 // Process only complete 480-sample frames. The worker thread
660 // guarantees render_count == capture_count and both are multiples of
661 // 480, so no partial frames should occur. If they do (defensive), the
662 // tail samples pass through unprocessed rather than corrupting AEC3
663 // with padded data.
664 while (render_offset + webrtc_frame_size <= render_count &&
665 capture_offset + webrtc_frame_size <= capture_count) {
666
667 // STEP 1: Feed render signal (what's playing to speakers)
668 for (int channel = 0; channel < channels; channel++)
669 for (int frame = 0; frame < 480; frame++)
670 render_channels[channel][frame] =
671 render_samples[render_offset + frame * channels + channel] *
672 32768.0f;
673 render_buf->SplitIntoFrequencyBands();
674 wrapper->aec3->AnalyzeRender(render_buf);
675 render_buf->MergeFrequencyBands();
676 g_render_frames_fed.fetch_add(1, std::memory_order_relaxed);
677 render_offset += webrtc_frame_size;
678
679 // STEP 2: Process capture (microphone input)
680 for (int channel = 0; channel < channels; channel++)
681 for (int frame = 0; frame < 480; frame++)
682 capture_channels[channel][frame] =
683 processed_output[capture_offset + frame * channels +
684 channel] *
685 32768.0f;
686 wrapper->aec3->AnalyzeCapture(capture_buf);
687 capture_buf->SplitIntoFrequencyBands();
688 wrapper->aec3->ProcessCapture(capture_buf, false);
689 capture_buf->MergeFrequencyBands();
690
691 // Scale back to float range and soft clip
692 for (int j = 0; j < webrtc_frame_size; j++) {
693 float sample =
694 capture_channels[j % channels][j / channels] / 32768.0f;
695 processed_output[capture_offset + j] =
696 soft_clip(sample, 0.6f, 2.5f);
697 }
698
699 // Log AEC3 metrics periodically
700 static int duplex_log_count = 0;
701 if (++duplex_log_count % 100 == 1) {
702 webrtc::EchoControl::Metrics metrics =
703 wrapper->aec3->GetMetrics();
704 log_debug("AEC3 DUPLEX: ERL=%.1f ERLE=%.1f delay=%dms",
705 metrics.echo_return_loss,
706 metrics.echo_return_loss_enhancement, metrics.delay_ms);
708 metrics.echo_return_loss,
709 metrics.echo_return_loss_enhancement, metrics.delay_ms);
710 }
711 capture_offset += webrtc_frame_size;
712 }
713 }
714 }
715 }
716 }
717
718 // Debug WAV recording (after AEC3)
719 if (pipeline->debug_wav_aec3_out) {
721 processed_output, capture_count);
722 }
723
724 asciichat_error_t result =
725 audio_processor_process(pipeline->processor, processed_output,
726 processed_output, (size_t)capture_count);
727 if (result != ASCIICHAT_OK)
728 log_error("Audio enhancement failed: %d", result);
729}
void audio_analysis_set_aec3_metrics(double echo_return_loss, double echo_return_loss_enhancement, uint64_t delay_ns)
Set AEC3 echo cancellation metrics.
Definition analysis.c:556
float soft_clip(float sample, float threshold, float steepness)
Apply soft clipping to a sample.
Definition effects.c:307
float smoothstep(float t)
Compute smoothstep interpolation.
Definition effects.c:337
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
asciichat_error_t audio_processor_process(audio_processor_t *p, const float *input, float *output, size_t count)
Definition processor.c:173
const char * platform_getenv(const char *name)
Definition system.c:45
int wav_writer_write(wav_writer_t *writer, const float *samples, int num_samples)
Write audio samples to WAV file.
Definition wav_writer.c:107

References client_audio_pipeline_t::aec3_capture_buffer, client_audio_pipeline_t::aec3_render_buffer, ASCIICHAT_OK, audio_analysis_set_aec3_metrics(), audio_processor_process(), client_audio_pipeline_t::capture_fadein_remaining, client_audio_pipeline_config_t::channels, client_audio_pipeline_t::config, client_audio_pipeline_t::debug_wav_aec3_in, client_audio_pipeline_t::debug_wav_aec3_out, client_audio_pipeline_flags_t::echo_cancel, client_audio_pipeline_t::echo_canceller, client_audio_pipeline_t::flags, log_debug, log_error, log_warn, log_warn_every, platform_getenv(), client_audio_pipeline_t::processor, client_audio_pipeline_config_t::sample_rate, smoothstep(), soft_clip(), and wav_writer_write().

◆ client_audio_pipeline_reset()

void client_audio_pipeline_reset ( client_audio_pipeline_t * pipeline)

Reset pipeline state.

Parameters
pipelinePipeline instance

Resets echo canceller, jitter buffer, and filter states. Call when starting a new audio session.

Reset pipeline state

Definition at line 745 of file client_pipeline.cpp.

745 {
746 if (!pipeline)
747 return;
748
749 if (audio_processor_reset(pipeline->processor) != ASCIICHAT_OK) {
750 log_error("Failed to reset audio processor: %d", GET_ERRNO());
751 return;
752 }
753
754 // Reset global counters
755 g_render_frames_fed.store(0, std::memory_order_relaxed);
756 g_max_render_rms.store(0.0f, std::memory_order_relaxed);
757
758 log_info("Pipeline state reset");
759}
#define GET_ERRNO()
asciichat_error_t audio_processor_reset(audio_processor_t *p)
Definition processor.c:62

References ASCIICHAT_OK, audio_processor_reset(), GET_ERRNO, log_error, log_info, and client_audio_pipeline_t::processor.

◆ client_audio_pipeline_set_flags()

void client_audio_pipeline_set_flags ( client_audio_pipeline_t * pipeline,
client_audio_pipeline_flags_t flags )

Set component enable flags.

Parameters
pipelinePipeline instance
flagsNew flags to set

Thread-safe. Changes take effect on next capture/playback call.

Definition at line 444 of file client_pipeline.cpp.

445 {
446 if (!pipeline)
447 return;
448 // No mutex needed - flags are only read by capture thread
449 pipeline->flags = flags;
450 audio_processor_flags_t processor_flags;
451 processor_flags.agc = flags.agc;
452 processor_flags.compressor = flags.compressor;
453 processor_flags.noise_gate = flags.noise_gate;
454 processor_flags.highpass = flags.highpass;
455 processor_flags.lowpass = flags.lowpass;
456 audio_processor_set_flags(pipeline->processor, processor_flags);
457}
void audio_processor_set_flags(audio_processor_t *p, audio_processor_flags_t flags)
Definition processor.c:167
audio processor config keeps the values that move through the subsystem: channels,...
Definition processor.h:26

References audio_processor_flags_t::agc, client_audio_pipeline_flags_t::agc, audio_processor_set_flags(), audio_processor_flags_t::compressor, client_audio_pipeline_flags_t::compressor, client_audio_pipeline_t::flags, audio_processor_flags_t::highpass, client_audio_pipeline_flags_t::highpass, audio_processor_flags_t::lowpass, client_audio_pipeline_flags_t::lowpass, audio_processor_flags_t::noise_gate, client_audio_pipeline_flags_t::noise_gate, and client_audio_pipeline_t::processor.

◆ client_audio_pipeline_voice_detected()

bool client_audio_pipeline_voice_detected ( client_audio_pipeline_t * pipeline)

Check if VAD detected voice activity in last capture.

Parameters
pipelinePipeline instance
Returns
true if voice was detected, false otherwise