Debian Codegraph @

Xpjproject/pjsip-apps/src/samples/aidemo.c

raw symbols SCIP
1 /*
2 * Copyright (C) 2026 Teluu Inc. (http://www.teluu.com)
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18
19 /*
20 * aidemo.c
21 *
22 * PURPOSE:
23 * Demonstrate the AI media port by connecting the local sound device
24 * (or null audio) to the OpenAI Realtime API. Captures microphone
25 * audio, sends it to OpenAI, and plays the AI response through the
26 * speaker.
27 *
28 * USAGE:
29 * aidemo [options]
30 *
31 * The OPENAI_API_KEY environment variable must be set.
32 *
33 * Options:
34 * -m URL WebSocket URL for the OpenAI endpoint.
35 * -n Use null audio (no sound device). Useful for
36 * headless testing.
37 * -d seconds Duration in seconds for null-audio mode (default 10).
38 * -L N Set pjlib log level (0-6, default 4).
39 */
40
41 #include <pjmedia.h>
42 #include <pjmedia/ai_port.h>
43 #include <pjlib-util.h>
44 #include <pjlib.h>
45
46 #include <stdio.h>
47 #include <stdlib.h>
48
49 #define THIS_FILE "aidemo.c"
50
51 /* Audio ptime - port clock rate is derived from the AI backend */
52 #define PTIME_MS 20
53
54 /* Default sound device clock rate. 0 means match the AI backend's
55 * native rate (e.g. 24kHz for OpenAI). Override with -r option.
56 */
57 #define SND_CLOCK_RATE 0
58
59 /* Default OpenAI Realtime API URL */
60 #define DEFAULT_URL \
61 "wss://api.openai.com/v1/realtime?model=gpt-4o-mini-realtime-preview"
62
63 /* Application data */
64 static struct app_t
65 {
66 pj_caching_pool cp;
67 pj_pool_t *pool;
68 pjmedia_endpt *med_endpt;
69
70 pj_ioqueue_t *ioqueue;
71 pj_timer_heap_t *timer_heap;
72 pj_thread_t *worker_thread;
73 pj_bool_t worker_quit;
74
75 pjmedia_ai_backend *backend;
76 pjmedia_ai_port *ai_port;
77
78 /* Sound device mode */
79 pjmedia_snd_port *snd_port;
80 pjmedia_port *resamp_port;
81
82 /* Null audio mode */
83 pj_bool_t null_audio;
84 int duration;
85 pjmedia_port *null_port;
86 pjmedia_master_port *master_port;
87
88 volatile pj_bool_t connected;
89
90 char url[512];
91 int log_level;
92 unsigned snd_clock_rate;
93 } app;
94
95
96 static int app_perror(const char *sender, const char *title,
97 pj_status_t status)
98 {
99 char errmsg[PJ_ERR_MSG_SIZE];
100 pj_strerror(status, errmsg, sizeof(errmsg));
101 PJ_LOG(1, (sender, "%s: %s [code=%d]", title, errmsg, status));
102 return 1;
103 }
104
105
106 /*
107 * Worker thread: polls ioqueue and timer_heap for WebSocket I/O.
108 * Uses a short poll timeout to ensure low-latency delivery of
109 * WebSocket audio data.
110 */
111 static int worker_thread_func(void *arg)
112 {
113 PJ_UNUSED_ARG(arg);
114
115 while (!app.worker_quit) {
116 pj_time_val timeout = {0, 10};
117 int c;
118
119 c = pj_timer_heap_poll(app.timer_heap, &timeout);
120 if (c == 0) {
121 timeout.sec = 0;
122 timeout.msec = 10;
123 }
124 if (timeout.msec > 10)
125 timeout.msec = 10;
126
127 pj_ioqueue_poll(app.ioqueue, &timeout);
128 }
129
130 return 0;
131 }
132
133
134 /*
135 * AI port event callback.
136 */
137 static void on_ai_event(pjmedia_ai_port *ai_port,
138 const pjmedia_ai_event *event)
139 {
140 PJ_UNUSED_ARG(ai_port);
141
142 switch (event->type) {
143 case PJMEDIA_AI_EVENT_CONNECTED:
144 PJ_LOG(3, (THIS_FILE, "Connected to AI service"));
145 app.connected = PJ_TRUE;
146 break;
147
148 case PJMEDIA_AI_EVENT_DISCONNECTED:
149 if (event->status == PJ_SUCCESS) {
150 PJ_LOG(3, (THIS_FILE, "Disconnected from AI service"));
151 } else {
152 PJ_PERROR(3, (THIS_FILE, event->status,
153 "AI service disconnected with error"));
154 }
155 app.connected = PJ_FALSE;
156 break;
157
158 case PJMEDIA_AI_EVENT_TRANSCRIPT:
159 printf("\n[AI] %.*s", (int)event->text.slen, event->text.ptr);
160 fflush(stdout);
161 break;
162
163 case PJMEDIA_AI_EVENT_RESPONSE_START:
164 PJ_LOG(4, (THIS_FILE, "AI response started"));
165 break;
166
167 case PJMEDIA_AI_EVENT_RESPONSE_DONE:
168 printf("\n");
169 PJ_LOG(4, (THIS_FILE, "AI response done"));
170 break;
171
172 case PJMEDIA_AI_EVENT_SPEECH_STARTED:
173 PJ_LOG(4, (THIS_FILE, "Speech detected"));
174 break;
175
176 case PJMEDIA_AI_EVENT_SPEECH_STOPPED:
177 PJ_LOG(4, (THIS_FILE, "Speech ended"));
178 break;
179 }
180 }
181
182
183 static void print_usage(void)
184 {
185 puts("aidemo - AI Media Port Demo (OpenAI Realtime API)");
186 puts("");
187 puts("Usage: aidemo [options]");
188 puts("");
189 puts("Options:");
190 puts(" -m URL WebSocket URL for OpenAI endpoint");
191 puts(" -r N Sound device clock rate in Hz (default: AI native)");
192 puts(" -n Use null audio (no sound device)");
193 puts(" -d seconds Duration for null-audio mode (default 10)");
194 puts(" -L N Set log level (0-6, default 4)");
195 puts("");
196 puts("Environment:");
197 puts(" OPENAI_API_KEY Required. Your OpenAI API key.");
198 puts("");
199 puts("The demo captures microphone audio, sends it to the OpenAI");
200 puts("Realtime API, and plays the AI response through the speaker.");
201 puts("With -n, runs headless with silence input for the specified");
202 puts("duration. Press ENTER to quit (in normal mode).");
203 }
204
205
206 int main(int argc, char *argv[])
207 {
208 const char *api_key;
209 pj_str_t url_str;
210 pj_str_t token_str;
211 pjmedia_ai_port_param ai_param;
212 pj_ssl_sock_param ssl_param;
213 pjmedia_port *ai_media_port;
214 unsigned ai_rate, ai_ccnt, ai_spf, ai_bps;
215 char tmp[10];
216 int c;
217 pj_status_t status;
218
219 /* Defaults */
220 pj_bzero(&app, sizeof(app));
221 pj_ansi_strxcpy(app.url, DEFAULT_URL, sizeof(app.url));
222 app.log_level = 4;
223 app.snd_clock_rate = SND_CLOCK_RATE;
224 app.duration = 10;
225
226 /* Parse args */
227 while ((c = pj_getopt(argc, argv, "m:L:r:nd:h")) != -1) {
228 switch (c) {
229 case 'm':
230 pj_ansi_strxcpy(app.url, pj_optarg, sizeof(app.url));
231 break;
232 case 'L':
233 app.log_level = atoi(pj_optarg);
234 break;
235 case 'r':
236 app.snd_clock_rate = (unsigned)atoi(pj_optarg);
237 break;
238 case 'n':
239 app.null_audio = PJ_TRUE;
240 break;
241 case 'd':
242 app.duration = atoi(pj_optarg);
243 if (app.duration <= 0) app.duration = 10;
244 break;
245 case 'h':
246 print_usage();
247 return 0;
248 default:
249 print_usage();
250 return 1;
251 }
252 }
253
254 /* Get API key from environment */
255 api_key = getenv("OPENAI_API_KEY");
256 if (!api_key || !*api_key) {
257 puts("Error: OPENAI_API_KEY environment variable is not set.");
258 puts("");
259 print_usage();
260 return 1;
261 }
262
263 /* Init PJLIB */
264 status = pj_init();
265 PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
266
267 pj_log_set_level(app.log_level);
268
269 /* Init PJLIB-UTIL (needed for JSON, base64) */
270 status = pjlib_util_init();
271 PJ_ASSERT_RETURN(status == PJ_SUCCESS, 1);
272
273 /* Create pool factory */
274 pj_caching_pool_init(&app.cp, &pj_pool_factory_default_policy, 0);
275
276 /* Create pool */
277 app.pool = pj_pool_create(&app.cp.factory, "aidemo", 4096, 4096,
278 NULL);
279
280 /* Create media endpoint with its own internal ioqueue.
281 * Pass 0 worker threads since this demo doesn't use RTP.
282 */
283 status = pjmedia_endpt_create(&app.cp.factory, NULL, 0,
284 &app.med_endpt);
285 if (status != PJ_SUCCESS) {
286 app_perror(THIS_FILE, "Error creating media endpoint", status);
287 goto on_error;
288 }
289
290 /* Create ioqueue and timer heap for WebSocket I/O */
291 status = pj_ioqueue_create(app.pool, 16, &app.ioqueue);
292 if (status != PJ_SUCCESS) {
293 app_perror(THIS_FILE, "Error creating ioqueue", status);
294 goto on_error;
295 }
296
297 status = pj_timer_heap_create(app.pool, 100, &app.timer_heap);
298 if (status != PJ_SUCCESS) {
299 app_perror(THIS_FILE, "Error creating timer heap", status);
300 goto on_error;
301 }
302
303 /* Start worker thread for WebSocket ioqueue and timer polling */
304 status = pj_thread_create(app.pool, "ai_worker",
305 &worker_thread_func, NULL,
306 0, 0, &app.worker_thread);
307 if (status != PJ_SUCCESS) {
308 app_perror(THIS_FILE, "Error creating worker thread", status);
309 goto on_error;
310 }
311
312 /* Create OpenAI backend */
313 status = pjmedia_ai_openai_backend_create(app.pool, &app.backend);
314 if (status != PJ_SUCCESS) {
315 app_perror(THIS_FILE, "Error creating OpenAI backend", status);
316 goto on_error;
317 }
318
319 /* Create AI port.
320 * Port rate is derived from the backend's native rate (24kHz for
321 * OpenAI). The conference bridge / sound port handles resampling
322 * if the sound device uses a different rate.
323 */
324 pjmedia_ai_port_param_default(&ai_param);
325 ai_param.ioqueue = app.ioqueue;
326 ai_param.timer_heap = app.timer_heap;
327 ai_param.cb.on_event = &on_ai_event;
328 ai_param.backend = app.backend;
329
330 /* To enable TLS certificate verification, set verify_peer=PJ_TRUE
331 * and supply a CA certificate via pj_ssl_cert_load_from_files()
332 * + pj_ssl_sock_set_certificate() on the ssl_param.
333 */
334 pj_ssl_sock_param_default(&ssl_param);
335 ai_param.ssl_param = &ssl_param;
336
337 status = pjmedia_ai_port_create(app.pool, &ai_param, &app.ai_port);
338 if (status != PJ_SUCCESS) {
339 app_perror(THIS_FILE, "Error creating AI port", status);
340 goto on_error;
341 }
342
343 ai_media_port = pjmedia_ai_port_get_port(app.ai_port);
344
345 /* Get port info to derive clock settings for sound device */
346 ai_rate = PJMEDIA_PIA_SRATE(&ai_media_port->info);
347 ai_ccnt = PJMEDIA_PIA_CCNT(&ai_media_port->info);
348 ai_spf = PJMEDIA_PIA_SPF(&ai_media_port->info);
349 ai_bps = PJMEDIA_PIA_BITS(&ai_media_port->info);
350
351 if (app.null_audio) {
352 /*
353 * Null audio mode: use a null_port + master_port to drive
354 * the clock. The null port provides silence as input and
355 * discards output. Useful for headless/CI testing.
356 */
357 status = pjmedia_null_port_create(app.pool, ai_rate, ai_ccnt,
358 ai_spf, ai_bps,
359 &app.null_port);
360 if (status != PJ_SUCCESS) {
361 app_perror(THIS_FILE, "Error creating null port", status);
362 goto on_error;
363 }
364
365 /* Master port: upstream=null_port, downstream=ai_port.
366 * This drives get_frame on null_port, put_frame on ai_port,
367 * and vice versa every ptime.
368 */
369 status = pjmedia_master_port_create(app.pool,
370 app.null_port,
371 ai_media_port,
372 0, &app.master_port);
373 if (status != PJ_SUCCESS) {
374 app_perror(THIS_FILE, "Error creating master port", status);
375 goto on_error;
376 }
377
378 status = pjmedia_master_port_start(app.master_port);
379 if (status != PJ_SUCCESS) {
380 app_perror(THIS_FILE, "Error starting master port", status);
381 goto on_error;
382 }
383
384 PJ_LOG(3, (THIS_FILE, "Null audio mode, duration=%ds",
385 app.duration));
386 } else {
387 unsigned snd_rate = app.snd_clock_rate ? app.snd_clock_rate
388 : ai_rate;
389 unsigned snd_spf = snd_rate * PTIME_MS / 1000;
390
391 /* Create bidirectional sound port at a standard rate. */
392 status = pjmedia_snd_port_create(
393 app.pool,
394 -1, /* capture dev (default) */
395 -1, /* playback dev (default) */
396 snd_rate,
397 ai_ccnt,
398 snd_spf,
399 ai_bps,
400 0, /* options */
401 &app.snd_port);
402 if (status != PJ_SUCCESS) {
403 app_perror(THIS_FILE, "Error creating sound device", status);
404 goto on_error;
405 }
406
407 /* Enable AEC to suppress speaker-to-mic echo. Without this,
408 * the AI's own playback would be picked up by the microphone
409 * and sent back, causing the server VAD to trigger turn
410 * detection and cancel the AI response mid-sentence.
411 * AEC allows barge-in (user can interrupt the AI naturally).
412 */
413 status = pjmedia_snd_port_set_ec(app.snd_port, app.pool,
414 200, 0);
415 if (status != PJ_SUCCESS) {
416 PJ_PERROR(3, (THIS_FILE, status,
417 "Warning: failed to enable AEC"));
418 }
419
420 /* Create resample port if sound device rate differs from
421 * the AI port's native rate.
422 */
423 if (snd_rate != ai_rate) {
424 status = pjmedia_resample_port_create(
425 app.pool, ai_media_port, snd_rate,
426 PJMEDIA_RESAMPLE_DONT_DESTROY_DN,
427 &app.resamp_port);
428 if (status != PJ_SUCCESS) {
429 app_perror(THIS_FILE, "Error creating resample port",
430 status);
431 goto on_error;
432 }
433 }
434
435 /* Connect sound port to AI port (via resample port if needed) */
436 status = pjmedia_snd_port_connect(app.snd_port,
437 app.resamp_port ?
438 app.resamp_port :
439 ai_media_port);
440 if (status != PJ_SUCCESS) {
441 app_perror(THIS_FILE, "Error connecting sound to AI port",
442 status);
443 goto on_error;
444 }
445 }
446
447 /* Connect to OpenAI */
448 PJ_LOG(3, (THIS_FILE, "Connecting to %s ...", app.url));
449
450 url_str = pj_str(app.url);
451 token_str = pj_str((char*)api_key);
452
453 status = pjmedia_ai_port_connect(app.ai_port, &url_str,
454 &token_str);
455 if (status != PJ_SUCCESS) {
456 app_perror(THIS_FILE, "Error initiating AI connection", status);
457 goto on_error;
458 }
459
460 /* Wait for connection */
461 {
462 int wait_ms = 0;
463 while (!app.connected && wait_ms < 15000) {
464 pj_thread_sleep(100);
465 wait_ms += 100;
466 }
467 if (!app.connected) {
468 PJ_LOG(1, (THIS_FILE,
469 "Timeout waiting for AI service connection"));
470 goto on_error;
471 }
472 }
473
474 PJ_LOG(3, (THIS_FILE, "AI service connected."));
475
476 if (app.null_audio) {
477 /* In null audio mode, run for the specified duration */
478 PJ_LOG(3, (THIS_FILE, "Running with null audio for %d seconds..",
479 app.duration));
480 pj_thread_sleep(app.duration * 1000);
481 PJ_LOG(3, (THIS_FILE, "Duration elapsed, shutting down"));
482 } else {
483 puts("");
484 puts("==========================================");
485 puts(" AI Demo - OpenAI Realtime API");
486 puts(" Speak into your microphone.");
487 puts(" AI responses will be played back and");
488 puts(" transcripts shown below.");
489 puts(" Press ENTER to quit.");
490 puts("==========================================");
491 puts("");
492
493 if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
494 puts("EOF on stdin, quitting..");
495 }
496 }
497
498 /* Cleanup */
499 on_error:
500 PJ_LOG(3, (THIS_FILE, "Shutting down.."));
501
502 /* Stop the audio clock first so put_frame/get_frame stop */
503 if (app.master_port)
504 pjmedia_master_port_stop(app.master_port);
505
506 if (app.snd_port)
507 pjmedia_snd_port_disconnect(app.snd_port);
508
509 /* Disconnect AI service while worker thread still polls ioqueue,
510 * so the WebSocket close handshake can complete.
511 */
512 if (app.ai_port && app.connected) {
513 pjmedia_ai_port_disconnect(app.ai_port);
514 pj_thread_sleep(500);
515 }
516
517 /* Now stop worker thread */
518 if (app.worker_thread) {
519 app.worker_quit = PJ_TRUE;
520 pj_thread_join(app.worker_thread);
521 pj_thread_destroy(app.worker_thread);
522 }
523
524 /* Destroy master port (null audio mode) */
525 if (app.master_port)
526 pjmedia_master_port_destroy(app.master_port, PJ_FALSE);
527
528 /* Destroy null port */
529 if (app.null_port)
530 pjmedia_port_destroy(app.null_port);
531
532 /* Destroy sound port */
533 if (app.snd_port)
534 pjmedia_snd_port_destroy(app.snd_port);
535
536 /* Destroy resample port (does NOT destroy downstream AI port
537 * because PJMEDIA_RESAMPLE_DONT_DESTROY_DN was used).
538 */
539 if (app.resamp_port)
540 pjmedia_port_destroy(app.resamp_port);
541
542 /* Destroy AI port (releases websock, pools, grp_lock) */
543 if (app.ai_port)
544 pjmedia_port_destroy(pjmedia_ai_port_get_port(app.ai_port));
545
546 /* Destroy media endpoint */
547 if (app.med_endpt)
548 pjmedia_endpt_destroy(app.med_endpt);
549
550 /* Destroy WebSocket ioqueue and timer heap */
551 if (app.ioqueue)
552 pj_ioqueue_destroy(app.ioqueue);
553 if (app.timer_heap)
554 pj_timer_heap_destroy(app.timer_heap);
555
556 /* Release pool */
557 if (app.pool)
558 pj_pool_release(app.pool);
559
560 pj_caching_pool_destroy(&app.cp);
561 pj_shutdown();
562
563 return 0;
564 }