1 /* $Id$ */
2 /*
3  * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
4  * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 #include "pjsua_app.h"
21 
22 #define THIS_FILE	"pjsua_app.c"
23 
24 //#define STEREO_DEMO
25 //#define TRANSPORT_ADAPTER_SAMPLE
26 //#define HAVE_MULTIPART_TEST
27 
28 /* Ringtones		    US	       UK  */
29 #define RINGBACK_FREQ1	    440	    /* 400 */
30 #define RINGBACK_FREQ2	    480	    /* 450 */
31 #define RINGBACK_ON	    2000    /* 400 */
32 #define RINGBACK_OFF	    4000    /* 200 */
33 #define RINGBACK_CNT	    1	    /* 2   */
34 #define RINGBACK_INTERVAL   4000    /* 2000 */
35 
36 #define RING_FREQ1	    800
37 #define RING_FREQ2	    640
38 #define RING_ON		    200
39 #define RING_OFF	    100
40 #define RING_CNT	    3
41 #define RING_INTERVAL	    3000
42 
43 #define current_acc	pjsua_acc_get_default()
44 
45 #ifdef STEREO_DEMO
46 static void stereo_demo();
47 #endif
48 
49 #ifdef USE_GUI
50 pj_bool_t showNotification(pjsua_call_id call_id);
51 #endif
52 
53 static void ringback_start(pjsua_call_id call_id);
54 static void ring_start(pjsua_call_id call_id);
55 static void ring_stop(pjsua_call_id call_id);
56 static pj_status_t app_init(void);
57 static pj_status_t app_destroy(void);
58 
59 static pjsua_app_cfg_t app_cfg;
60 pj_str_t		    uri_arg;
61 pj_bool_t		    app_running	= PJ_FALSE;
62 
63 /*****************************************************************************
64  * Configuration manipulation
65  */
66 
67 /*****************************************************************************
68  * Callback
69  */
ringback_start(pjsua_call_id call_id)70 static void ringback_start(pjsua_call_id call_id)
71 {
72     if (app_config.no_tones)
73 	return;
74 
75     if (app_config.call_data[call_id].ringback_on)
76 	return;
77 
78     app_config.call_data[call_id].ringback_on = PJ_TRUE;
79 
80     if (++app_config.ringback_cnt==1 &&
81 	app_config.ringback_slot!=PJSUA_INVALID_ID)
82     {
83 	pjsua_conf_connect(app_config.ringback_slot, 0);
84     }
85 }
86 
ring_stop(pjsua_call_id call_id)87 static void ring_stop(pjsua_call_id call_id)
88 {
89     if (app_config.no_tones)
90 	return;
91 
92     if (app_config.call_data[call_id].ringback_on) {
93 	app_config.call_data[call_id].ringback_on = PJ_FALSE;
94 
95 	pj_assert(app_config.ringback_cnt>0);
96 	if (--app_config.ringback_cnt == 0 &&
97 	    app_config.ringback_slot!=PJSUA_INVALID_ID)
98 	{
99 	    pjsua_conf_disconnect(app_config.ringback_slot, 0);
100 	    pjmedia_tonegen_rewind(app_config.ringback_port);
101 	}
102     }
103 
104     if (app_config.call_data[call_id].ring_on) {
105 	app_config.call_data[call_id].ring_on = PJ_FALSE;
106 
107 	pj_assert(app_config.ring_cnt>0);
108 	if (--app_config.ring_cnt == 0 &&
109 	    app_config.ring_slot!=PJSUA_INVALID_ID)
110 	{
111 	    pjsua_conf_disconnect(app_config.ring_slot, 0);
112 	    pjmedia_tonegen_rewind(app_config.ring_port);
113 	}
114     }
115 }
116 
ring_start(pjsua_call_id call_id)117 static void ring_start(pjsua_call_id call_id)
118 {
119     if (app_config.no_tones)
120 	return;
121 
122     if (app_config.call_data[call_id].ring_on)
123 	return;
124 
125     app_config.call_data[call_id].ring_on = PJ_TRUE;
126 
127     if (++app_config.ring_cnt==1 &&
128 	app_config.ring_slot!=PJSUA_INVALID_ID)
129     {
130 	pjsua_conf_connect(app_config.ring_slot, 0);
131     }
132 }
133 
134 /* Callback from timer when the maximum call duration has been
135  * exceeded.
136  */
call_timeout_callback(pj_timer_heap_t * timer_heap,struct pj_timer_entry * entry)137 static void call_timeout_callback(pj_timer_heap_t *timer_heap,
138 				  struct pj_timer_entry *entry)
139 {
140     pjsua_call_id call_id = entry->id;
141     pjsua_msg_data msg_data_;
142     pjsip_generic_string_hdr warn;
143     pj_str_t hname = pj_str("Warning");
144     pj_str_t hvalue = pj_str("399 pjsua \"Call duration exceeded\"");
145 
146     PJ_UNUSED_ARG(timer_heap);
147 
148     if (call_id == PJSUA_INVALID_ID) {
149 	PJ_LOG(1,(THIS_FILE, "Invalid call ID in timer callback"));
150 	return;
151     }
152 
153     /* Add warning header */
154     pjsua_msg_data_init(&msg_data_);
155     pjsip_generic_string_hdr_init2(&warn, &hname, &hvalue);
156     pj_list_push_back(&msg_data_.hdr_list, &warn);
157 
158     /* Call duration has been exceeded; disconnect the call */
159     PJ_LOG(3,(THIS_FILE, "Duration (%d seconds) has been exceeded "
160 			 "for call %d, disconnecting the call",
161 			 app_config.duration, call_id));
162     entry->id = PJSUA_INVALID_ID;
163     pjsua_call_hangup(call_id, 200, NULL, &msg_data_);
164 }
165 
166 /*
167  * Handler when invite state has changed.
168  */
on_call_state(pjsua_call_id call_id,pjsip_event * e)169 static void on_call_state(pjsua_call_id call_id, pjsip_event *e)
170 {
171     pjsua_call_info call_info;
172 
173     PJ_UNUSED_ARG(e);
174 
175     pjsua_call_get_info(call_id, &call_info);
176 
177     if (call_info.state == PJSIP_INV_STATE_DISCONNECTED) {
178 
179 	/* Stop all ringback for this call */
180 	ring_stop(call_id);
181 
182 	/* Cancel duration timer, if any */
183 	if (app_config.call_data[call_id].timer.id != PJSUA_INVALID_ID) {
184 	    app_call_data *cd = &app_config.call_data[call_id];
185 	    pjsip_endpoint *endpt = pjsua_get_pjsip_endpt();
186 
187 	    cd->timer.id = PJSUA_INVALID_ID;
188 	    pjsip_endpt_cancel_timer(endpt, &cd->timer);
189 	}
190 
191 	/* Rewind play file when hangup automatically,
192 	 * since file is not looped
193 	 */
194 	if (app_config.auto_play_hangup)
195 	    pjsua_player_set_pos(app_config.wav_id, 0);
196 
197 
198 	PJ_LOG(3,(THIS_FILE, "Call %d is DISCONNECTED [reason=%d (%.*s)]",
199 		  call_id,
200 		  call_info.last_status,
201 		  (int)call_info.last_status_text.slen,
202 		  call_info.last_status_text.ptr));
203 
204 	if (call_id == current_call) {
205 	    find_next_call();
206 	}
207 
208 	/* Dump media state upon disconnected.
209 	 * Moved to on_stream_destroyed() since media has been deactivated
210 	 * upon disconnection.
211 	 */
212 	if (0) {
213 	    PJ_LOG(5,(THIS_FILE,
214 		      "Call %d disconnected, dumping media stats..",
215 		      call_id));
216 	    log_call_dump(call_id);
217 	}
218 
219     } else {
220 
221 	if (app_config.duration != PJSUA_APP_NO_LIMIT_DURATION &&
222 	    call_info.state == PJSIP_INV_STATE_CONFIRMED)
223 	{
224 	    /* Schedule timer to hangup call after the specified duration */
225 	    app_call_data *cd = &app_config.call_data[call_id];
226 	    pjsip_endpoint *endpt = pjsua_get_pjsip_endpt();
227 	    pj_time_val delay;
228 
229 	    cd->timer.id = call_id;
230 	    delay.sec = app_config.duration;
231 	    delay.msec = 0;
232 	    pjsip_endpt_schedule_timer(endpt, &cd->timer, &delay);
233 	}
234 
235 	if (call_info.state == PJSIP_INV_STATE_EARLY) {
236 	    int code;
237 	    pj_str_t reason;
238 	    pjsip_msg *msg;
239 
240 	    /* This can only occur because of TX or RX message */
241 	    pj_assert(e->type == PJSIP_EVENT_TSX_STATE);
242 
243 	    if (e->body.tsx_state.type == PJSIP_EVENT_RX_MSG) {
244 		msg = e->body.tsx_state.src.rdata->msg_info.msg;
245 	    } else {
246 		msg = e->body.tsx_state.src.tdata->msg;
247 	    }
248 
249 	    code = msg->line.status.code;
250 	    reason = msg->line.status.reason;
251 
252 	    /* Start ringback for 180 for UAC unless there's SDP in 180 */
253 	    if (call_info.role==PJSIP_ROLE_UAC && code==180 &&
254 		msg->body == NULL &&
255 		call_info.media_status==PJSUA_CALL_MEDIA_NONE)
256 	    {
257 		ringback_start(call_id);
258 	    }
259 
260 	    PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s (%d %.*s)",
261 		      call_id, (int)call_info.state_text.slen,
262                       call_info.state_text.ptr, code,
263                       (int)reason.slen, reason.ptr));
264 	} else {
265 	    PJ_LOG(3,(THIS_FILE, "Call %d state changed to %.*s",
266 		      call_id,
267 		      (int)call_info.state_text.slen,
268 		      call_info.state_text.ptr));
269 	}
270 
271 	if (current_call==PJSUA_INVALID_ID)
272 	    current_call = call_id;
273 
274     }
275 }
276 
277 /*
278  * Handler when audio stream is destroyed.
279  */
on_stream_destroyed(pjsua_call_id call_id,pjmedia_stream * strm,unsigned stream_idx)280 static void on_stream_destroyed(pjsua_call_id call_id,
281                                 pjmedia_stream *strm,
282 				unsigned stream_idx)
283 {
284     PJ_UNUSED_ARG(strm);
285     if (1) {
286 	PJ_LOG(5,(THIS_FILE,
287 		  "Call %d stream %d destroyed, dumping media stats..",
288 		  call_id, stream_idx));
289 	log_call_dump(call_id);
290     }
291 }
292 
293 /**
294  * Handler when there is incoming call.
295  */
on_incoming_call(pjsua_acc_id acc_id,pjsua_call_id call_id,pjsip_rx_data * rdata)296 static void on_incoming_call(pjsua_acc_id acc_id, pjsua_call_id call_id,
297 			     pjsip_rx_data *rdata)
298 {
299     pjsua_call_info call_info;
300 
301     PJ_UNUSED_ARG(acc_id);
302     PJ_UNUSED_ARG(rdata);
303 
304     pjsua_call_get_info(call_id, &call_info);
305 
306     if (current_call==PJSUA_INVALID_ID)
307 	current_call = call_id;
308 
309 #ifdef USE_GUI
310     if (!showNotification(call_id))
311 	return;
312 #endif
313 
314     /* Start ringback */
315     if (call_info.rem_aud_cnt)
316     	ring_start(call_id);
317 
318     if (app_config.auto_answer > 0) {
319 	pjsua_call_setting opt;
320 
321 	pjsua_call_setting_default(&opt);
322 	opt.aud_cnt = app_config.aud_cnt;
323 	opt.vid_cnt = app_config.vid.vid_cnt;
324 
325 	pjsua_call_answer2(call_id, &opt, app_config.auto_answer, NULL,
326 			   NULL);
327     }
328 
329     if (app_config.auto_answer < 200) {
330 	char notif_st[80] = {0};
331 
332 #if PJSUA_HAS_VIDEO
333 	if (call_info.rem_offerer && call_info.rem_vid_cnt) {
334 	    snprintf(notif_st, sizeof(notif_st),
335 		     "To %s the video, type \"vid %s\" first, "
336 		     "before answering the call!\n",
337 		     (app_config.vid.vid_cnt? "reject":"accept"),
338 		     (app_config.vid.vid_cnt? "disable":"enable"));
339 	}
340 #endif
341 
342 	PJ_LOG(3,(THIS_FILE,
343 		  "Incoming call for account %d!\n"
344 		  "Media count: %d audio & %d video\n"
345 		  "%s"
346 		  "From: %.*s\n"
347 		  "To: %.*s\n"
348 		  "Press %s to answer or %s to reject call",
349 		  acc_id,
350 		  call_info.rem_aud_cnt,
351 		  call_info.rem_vid_cnt,
352 		  notif_st,
353 		  (int)call_info.remote_info.slen,
354 		  call_info.remote_info.ptr,
355 		  (int)call_info.local_info.slen,
356 		  call_info.local_info.ptr,
357 		  (app_config.use_cli?"ca a":"a"),
358 		  (app_config.use_cli?"g":"h")));
359     }
360 }
361 
362 /* General processing for media state. "mi" is the media index */
on_call_generic_media_state(pjsua_call_info * ci,unsigned mi,pj_bool_t * has_error)363 static void on_call_generic_media_state(pjsua_call_info *ci, unsigned mi,
364                                         pj_bool_t *has_error)
365 {
366     const char *status_name[] = {
367         "None",
368         "Active",
369         "Local hold",
370         "Remote hold",
371         "Error"
372     };
373 
374     PJ_UNUSED_ARG(has_error);
375 
376     pj_assert(ci->media[mi].status <= PJ_ARRAY_SIZE(status_name));
377     pj_assert(PJSUA_CALL_MEDIA_ERROR == 4);
378 
379     PJ_LOG(4,(THIS_FILE, "Call %d media %d [type=%s], status is %s",
380 	      ci->id, mi, pjmedia_type_name(ci->media[mi].type),
381 	      status_name[ci->media[mi].status]));
382 }
383 
384 /* Process audio media state. "mi" is the media index. */
on_call_audio_state(pjsua_call_info * ci,unsigned mi,pj_bool_t * has_error)385 static void on_call_audio_state(pjsua_call_info *ci, unsigned mi,
386                                 pj_bool_t *has_error)
387 {
388     PJ_UNUSED_ARG(has_error);
389 
390     /* Stop ringback */
391     ring_stop(ci->id);
392 
393     /* Connect ports appropriately when media status is ACTIVE or REMOTE HOLD,
394      * otherwise we should NOT connect the ports.
395      */
396     if (ci->media[mi].status == PJSUA_CALL_MEDIA_ACTIVE ||
397 	ci->media[mi].status == PJSUA_CALL_MEDIA_REMOTE_HOLD)
398     {
399 	pj_bool_t connect_sound = PJ_TRUE;
400 	pj_bool_t disconnect_mic = PJ_FALSE;
401 	pjsua_conf_port_id call_conf_slot;
402 
403 	call_conf_slot = ci->media[mi].stream.aud.conf_slot;
404 
405 	/* Loopback sound, if desired */
406 	if (app_config.auto_loop) {
407 	    pjsua_conf_connect(call_conf_slot, call_conf_slot);
408 	    connect_sound = PJ_FALSE;
409 	}
410 
411 	/* Automatically record conversation, if desired */
412 	if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID) {
413 	    pjsua_conf_connect(call_conf_slot, app_config.rec_port);
414 	}
415 
416 	/* Stream a file, if desired */
417 	if ((app_config.auto_play || app_config.auto_play_hangup) &&
418 	    app_config.wav_port != PJSUA_INVALID_ID)
419 	{
420 	    pjsua_conf_connect(app_config.wav_port, call_conf_slot);
421 	    connect_sound = PJ_FALSE;
422 	}
423 
424 	/* Stream AVI, if desired */
425 	if (app_config.avi_auto_play &&
426 	    app_config.avi_def_idx != PJSUA_INVALID_ID &&
427 	    app_config.avi[app_config.avi_def_idx].slot != PJSUA_INVALID_ID)
428 	{
429 	    pjsua_conf_connect(app_config.avi[app_config.avi_def_idx].slot,
430 			       call_conf_slot);
431 	    disconnect_mic = PJ_TRUE;
432 	}
433 
434 	/* Put call in conference with other calls, if desired */
435 	if (app_config.auto_conf) {
436 	    pjsua_call_id call_ids[PJSUA_MAX_CALLS];
437 	    unsigned call_cnt=PJ_ARRAY_SIZE(call_ids);
438 	    unsigned i;
439 
440 	    /* Get all calls, and establish media connection between
441 	     * this call and other calls.
442 	     */
443 	    pjsua_enum_calls(call_ids, &call_cnt);
444 
445 	    for (i=0; i<call_cnt; ++i) {
446 		if (call_ids[i] == ci->id)
447 		    continue;
448 
449 		if (!pjsua_call_has_media(call_ids[i]))
450 		    continue;
451 
452 		pjsua_conf_connect(call_conf_slot,
453 				   pjsua_call_get_conf_port(call_ids[i]));
454 		pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]),
455 		                   call_conf_slot);
456 
457 		/* Automatically record conversation, if desired */
458 		if (app_config.auto_rec && app_config.rec_port !=
459 					   PJSUA_INVALID_ID)
460 		{
461 		    pjsua_conf_connect(pjsua_call_get_conf_port(call_ids[i]),
462 				       app_config.rec_port);
463 		}
464 
465 	    }
466 
467 	    /* Also connect call to local sound device */
468 	    connect_sound = PJ_TRUE;
469 	}
470 
471 	/* Otherwise connect to sound device */
472 	if (connect_sound) {
473 	    pjsua_conf_connect(call_conf_slot, 0);
474 	    if (!disconnect_mic)
475 		pjsua_conf_connect(0, call_conf_slot);
476 
477 	    /* Automatically record conversation, if desired */
478 	    if (app_config.auto_rec && app_config.rec_port != PJSUA_INVALID_ID)
479 	    {
480 		pjsua_conf_connect(call_conf_slot, app_config.rec_port);
481 		pjsua_conf_connect(0, app_config.rec_port);
482 	    }
483 	}
484     }
485 }
486 
487 /* Process video media state. "mi" is the media index. */
on_call_video_state(pjsua_call_info * ci,unsigned mi,pj_bool_t * has_error)488 static void on_call_video_state(pjsua_call_info *ci, unsigned mi,
489                                 pj_bool_t *has_error)
490 {
491     if (ci->media_status != PJSUA_CALL_MEDIA_ACTIVE)
492 	return;
493 
494     arrange_window(ci->media[mi].stream.vid.win_in);
495 
496     PJ_UNUSED_ARG(has_error);
497 }
498 
499 /*
500  * Callback on media state changed event.
501  * The action may connect the call to sound device, to file, or
502  * to loop the call.
503  */
on_call_media_state(pjsua_call_id call_id)504 static void on_call_media_state(pjsua_call_id call_id)
505 {
506     pjsua_call_info call_info;
507     unsigned mi;
508     pj_bool_t has_error = PJ_FALSE;
509 
510     pjsua_call_get_info(call_id, &call_info);
511 
512     for (mi=0; mi<call_info.media_cnt; ++mi) {
513 	on_call_generic_media_state(&call_info, mi, &has_error);
514 
515 	switch (call_info.media[mi].type) {
516 	case PJMEDIA_TYPE_AUDIO:
517 	    on_call_audio_state(&call_info, mi, &has_error);
518 	    break;
519 	case PJMEDIA_TYPE_VIDEO:
520 	    on_call_video_state(&call_info, mi, &has_error);
521 	    break;
522 	default:
523 	    /* Make gcc happy about enum not handled by switch/case */
524 	    break;
525 	}
526     }
527 
528     if (has_error) {
529 	pj_str_t reason = pj_str("Media failed");
530 	pjsua_call_hangup(call_id, 500, &reason, NULL);
531     }
532 
533 #if PJSUA_HAS_VIDEO
534     /* Check if remote has just tried to enable video */
535     if (call_info.rem_offerer && call_info.rem_vid_cnt)
536     {
537 	int vid_idx;
538 
539 	/* Check if there is active video */
540 	vid_idx = pjsua_call_get_vid_stream_idx(call_id);
541 	if (vid_idx == -1 || call_info.media[vid_idx].dir == PJMEDIA_DIR_NONE) {
542 	    PJ_LOG(3,(THIS_FILE,
543 		      "Just rejected incoming video offer on call %d, "
544 		      "use \"vid call enable %d\" or \"vid call add\" to "
545 		      "enable video!", call_id, vid_idx));
546 	}
547     }
548 #endif
549 }
550 
551 /*
552  * DTMF callback.
553  */
554 /*
555 static void call_on_dtmf_callback(pjsua_call_id call_id, int dtmf)
556 {
557     PJ_LOG(3,(THIS_FILE, "Incoming DTMF on call %d: %c", call_id, dtmf));
558 }
559 */
560 
call_on_dtmf_callback2(pjsua_call_id call_id,const pjsua_dtmf_info * info)561 static void call_on_dtmf_callback2(pjsua_call_id call_id,
562 				   const pjsua_dtmf_info *info)
563 {
564     char duration[16];
565     char method[16];
566 
567     duration[0] = '\0';
568 
569     switch (info->method) {
570     case PJSUA_DTMF_METHOD_RFC2833:
571 	pj_ansi_snprintf(method, sizeof(method), "RFC2833");
572 	break;
573     case PJSUA_DTMF_METHOD_SIP_INFO:
574 	pj_ansi_snprintf(method, sizeof(method), "SIP INFO");
575 	pj_ansi_snprintf(duration, sizeof(duration), ":duration(%d)",
576 			 info->duration);
577 	break;
578     };
579     PJ_LOG(3,(THIS_FILE, "Incoming DTMF on call %d: %c%s, using %s method",
580 	   call_id, info->digit, duration, method));
581 }
582 
583 /*
584  * Redirection handler.
585  */
call_on_redirected(pjsua_call_id call_id,const pjsip_uri * target,const pjsip_event * e)586 static pjsip_redirect_op call_on_redirected(pjsua_call_id call_id,
587 					    const pjsip_uri *target,
588 					    const pjsip_event *e)
589 {
590     PJ_UNUSED_ARG(e);
591 
592     if (app_config.redir_op == PJSIP_REDIRECT_PENDING) {
593 	char uristr[PJSIP_MAX_URL_SIZE];
594 	int len;
595 
596 	len = pjsip_uri_print(PJSIP_URI_IN_FROMTO_HDR, target, uristr,
597 			      sizeof(uristr));
598 	if (len < 1) {
599 	    pj_ansi_strcpy(uristr, "--URI too long--");
600 	}
601 
602 	PJ_LOG(3,(THIS_FILE, "Call %d is being redirected to %.*s. "
603 		  "Press 'Ra' to accept+replace To header, 'RA' to accept, "
604 		  "'Rr' to reject, or 'Rd' to disconnect.",
605 		  call_id, len, uristr));
606     }
607 
608     return app_config.redir_op;
609 }
610 
611 /*
612  * Handler registration status has changed.
613  */
on_reg_state(pjsua_acc_id acc_id)614 static void on_reg_state(pjsua_acc_id acc_id)
615 {
616     PJ_UNUSED_ARG(acc_id);
617 
618     // Log already written.
619 }
620 
621 /*
622  * Handler for incoming presence subscription request
623  */
on_incoming_subscribe(pjsua_acc_id acc_id,pjsua_srv_pres * srv_pres,pjsua_buddy_id buddy_id,const pj_str_t * from,pjsip_rx_data * rdata,pjsip_status_code * code,pj_str_t * reason,pjsua_msg_data * msg_data_)624 static void on_incoming_subscribe(pjsua_acc_id acc_id,
625 				  pjsua_srv_pres *srv_pres,
626 				  pjsua_buddy_id buddy_id,
627 				  const pj_str_t *from,
628 				  pjsip_rx_data *rdata,
629 				  pjsip_status_code *code,
630 				  pj_str_t *reason,
631 				  pjsua_msg_data *msg_data_)
632 {
633     /* Just accept the request (the default behavior) */
634     PJ_UNUSED_ARG(acc_id);
635     PJ_UNUSED_ARG(srv_pres);
636     PJ_UNUSED_ARG(buddy_id);
637     PJ_UNUSED_ARG(from);
638     PJ_UNUSED_ARG(rdata);
639     PJ_UNUSED_ARG(code);
640     PJ_UNUSED_ARG(reason);
641     PJ_UNUSED_ARG(msg_data_);
642 }
643 
644 
645 /*
646  * Handler on buddy state changed.
647  */
on_buddy_state(pjsua_buddy_id buddy_id)648 static void on_buddy_state(pjsua_buddy_id buddy_id)
649 {
650     pjsua_buddy_info info;
651     pjsua_buddy_get_info(buddy_id, &info);
652 
653     PJ_LOG(3,(THIS_FILE, "%.*s status is %.*s, subscription state is %s "
654 			 "(last termination reason code=%d %.*s)",
655 	      (int)info.uri.slen,
656 	      info.uri.ptr,
657 	      (int)info.status_text.slen,
658 	      info.status_text.ptr,
659 	      info.sub_state_name,
660 	      info.sub_term_code,
661 	      (int)info.sub_term_reason.slen,
662 	      info.sub_term_reason.ptr));
663 }
664 
665 
666 /*
667  * Subscription state has changed.
668  */
on_buddy_evsub_state(pjsua_buddy_id buddy_id,pjsip_evsub * sub,pjsip_event * event)669 static void on_buddy_evsub_state(pjsua_buddy_id buddy_id,
670 				 pjsip_evsub *sub,
671 				 pjsip_event *event)
672 {
673     char event_info[80];
674 
675     PJ_UNUSED_ARG(sub);
676 
677     event_info[0] = '\0';
678 
679     if (event->type == PJSIP_EVENT_TSX_STATE &&
680 	    event->body.tsx_state.type == PJSIP_EVENT_RX_MSG)
681     {
682 	pjsip_rx_data *rdata = event->body.tsx_state.src.rdata;
683 	snprintf(event_info, sizeof(event_info),
684 		 " (RX %s)",
685 		 pjsip_rx_data_get_info(rdata));
686     }
687 
688     PJ_LOG(4,(THIS_FILE,
689 	      "Buddy %d: subscription state: %s (event: %s%s)",
690 	      buddy_id, pjsip_evsub_get_state_name(sub),
691 	      pjsip_event_str(event->type),
692 	      event_info));
693 
694 }
695 
696 
697 /**
698  * Incoming IM message (i.e. MESSAGE request)!
699  */
on_pager(pjsua_call_id call_id,const pj_str_t * from,const pj_str_t * to,const pj_str_t * contact,const pj_str_t * mime_type,const pj_str_t * text)700 static void on_pager(pjsua_call_id call_id, const pj_str_t *from,
701 		     const pj_str_t *to, const pj_str_t *contact,
702 		     const pj_str_t *mime_type, const pj_str_t *text)
703 {
704     /* Note: call index may be -1 */
705     PJ_UNUSED_ARG(call_id);
706     PJ_UNUSED_ARG(to);
707     PJ_UNUSED_ARG(contact);
708     PJ_UNUSED_ARG(mime_type);
709 
710     PJ_LOG(3,(THIS_FILE,"MESSAGE from %.*s: %.*s (%.*s)",
711 	      (int)from->slen, from->ptr,
712 	      (int)text->slen, text->ptr,
713 	      (int)mime_type->slen, mime_type->ptr));
714 }
715 
716 
717 /**
718  * Received typing indication
719  */
on_typing(pjsua_call_id call_id,const pj_str_t * from,const pj_str_t * to,const pj_str_t * contact,pj_bool_t is_typing)720 static void on_typing(pjsua_call_id call_id, const pj_str_t *from,
721 		      const pj_str_t *to, const pj_str_t *contact,
722 		      pj_bool_t is_typing)
723 {
724     PJ_UNUSED_ARG(call_id);
725     PJ_UNUSED_ARG(to);
726     PJ_UNUSED_ARG(contact);
727 
728     PJ_LOG(3,(THIS_FILE, "IM indication: %.*s %s",
729 	      (int)from->slen, from->ptr,
730 	      (is_typing?"is typing..":"has stopped typing")));
731 }
732 
733 
734 /**
735  * Call transfer request status.
736  */
on_call_transfer_status(pjsua_call_id call_id,int status_code,const pj_str_t * status_text,pj_bool_t final,pj_bool_t * p_cont)737 static void on_call_transfer_status(pjsua_call_id call_id,
738 				    int status_code,
739 				    const pj_str_t *status_text,
740 				    pj_bool_t final,
741 				    pj_bool_t *p_cont)
742 {
743     PJ_LOG(3,(THIS_FILE, "Call %d: transfer status=%d (%.*s) %s",
744 	      call_id, status_code,
745 	      (int)status_text->slen, status_text->ptr,
746 	      (final ? "[final]" : "")));
747 
748     if (status_code/100 == 2) {
749 	PJ_LOG(3,(THIS_FILE,
750 	          "Call %d: call transferred successfully, disconnecting call",
751 		  call_id));
752 	pjsua_call_hangup(call_id, PJSIP_SC_GONE, NULL, NULL);
753 	*p_cont = PJ_FALSE;
754     }
755 }
756 
757 
758 /*
759  * Notification that call is being replaced.
760  */
on_call_replaced(pjsua_call_id old_call_id,pjsua_call_id new_call_id)761 static void on_call_replaced(pjsua_call_id old_call_id,
762 			     pjsua_call_id new_call_id)
763 {
764     pjsua_call_info old_ci, new_ci;
765 
766     pjsua_call_get_info(old_call_id, &old_ci);
767     pjsua_call_get_info(new_call_id, &new_ci);
768 
769     PJ_LOG(3,(THIS_FILE, "Call %d with %.*s is being replaced by "
770 			 "call %d with %.*s",
771 			 old_call_id,
772 			 (int)old_ci.remote_info.slen, old_ci.remote_info.ptr,
773 			 new_call_id,
774 			 (int)new_ci.remote_info.slen, new_ci.remote_info.ptr));
775 }
776 
777 
778 /*
779  * NAT type detection callback.
780  */
on_nat_detect(const pj_stun_nat_detect_result * res)781 static void on_nat_detect(const pj_stun_nat_detect_result *res)
782 {
783     if (res->status != PJ_SUCCESS) {
784 	pjsua_perror(THIS_FILE, "NAT detection failed", res->status);
785     } else {
786 	PJ_LOG(3, (THIS_FILE, "NAT detected as %s", res->nat_type_name));
787     }
788 }
789 
790 
791 /*
792  * MWI indication
793  */
on_mwi_info(pjsua_acc_id acc_id,pjsua_mwi_info * mwi_info)794 static void on_mwi_info(pjsua_acc_id acc_id, pjsua_mwi_info *mwi_info)
795 {
796     pj_str_t body;
797 
798     PJ_LOG(3,(THIS_FILE, "Received MWI for acc %d:", acc_id));
799 
800     if (mwi_info->rdata->msg_info.ctype) {
801 	const pjsip_ctype_hdr *ctype = mwi_info->rdata->msg_info.ctype;
802 
803 	PJ_LOG(3,(THIS_FILE, " Content-Type: %.*s/%.*s",
804 	          (int)ctype->media.type.slen,
805 		  ctype->media.type.ptr,
806 		  (int)ctype->media.subtype.slen,
807 		  ctype->media.subtype.ptr));
808     }
809 
810     if (!mwi_info->rdata->msg_info.msg->body) {
811 	PJ_LOG(3,(THIS_FILE, "  no message body"));
812 	return;
813     }
814 
815     body.ptr = (char *)mwi_info->rdata->msg_info.msg->body->data;
816     body.slen = mwi_info->rdata->msg_info.msg->body->len;
817 
818     PJ_LOG(3,(THIS_FILE, " Body:\n%.*s", (int)body.slen, body.ptr));
819 }
820 
821 
822 /*
823  * Transport status notification
824  */
on_transport_state(pjsip_transport * tp,pjsip_transport_state state,const pjsip_transport_state_info * info)825 static void on_transport_state(pjsip_transport *tp,
826 			       pjsip_transport_state state,
827 			       const pjsip_transport_state_info *info)
828 {
829     char host_port[128];
830 
831     pj_addr_str_print(&tp->remote_name.host,
832 		      tp->remote_name.port, host_port, sizeof(host_port), 1);
833     switch (state) {
834     case PJSIP_TP_STATE_CONNECTED:
835 	{
836 	    PJ_LOG(3,(THIS_FILE, "SIP %s transport is connected to %s",
837 		     tp->type_name, host_port));
838 	}
839 	break;
840 
841     case PJSIP_TP_STATE_DISCONNECTED:
842 	{
843 	    char buf[100];
844 	    int len;
845 
846 	    len = pj_ansi_snprintf(buf, sizeof(buf), "SIP %s transport is "
847 	    	      "disconnected from %s", tp->type_name, host_port);
848 	    PJ_CHECK_TRUNC_STR(len, buf, sizeof(buf));
849 	    pjsua_perror(THIS_FILE, buf, info->status);
850 	}
851 	break;
852 
853     default:
854 	break;
855     }
856 
857 #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
858 
859     if (!pj_ansi_stricmp(tp->type_name, "tls") && info->ext_info &&
860 	(state == PJSIP_TP_STATE_CONNECTED ||
861 	 ((pjsip_tls_state_info*)info->ext_info)->
862 			         ssl_sock_info->verify_status != PJ_SUCCESS))
863     {
864 	pjsip_tls_state_info *tls_info = (pjsip_tls_state_info*)info->ext_info;
865 	pj_ssl_sock_info *ssl_sock_info = tls_info->ssl_sock_info;
866 	char buf[2048];
867 	const char *verif_msgs[32];
868 	unsigned verif_msg_cnt;
869 
870 	/* Dump server TLS cipher */
871 	PJ_LOG(4,(THIS_FILE, "TLS cipher used: 0x%06X/%s",
872 		  ssl_sock_info->cipher,
873 		  pj_ssl_cipher_name(ssl_sock_info->cipher) ));
874 
875 	/* Dump server TLS certificate */
876 	pj_ssl_cert_info_dump(ssl_sock_info->remote_cert_info, "  ",
877 			      buf, sizeof(buf));
878 	PJ_LOG(4,(THIS_FILE, "TLS cert info of %s:\n%s", host_port, buf));
879 
880 	/* Dump server TLS certificate verification result */
881 	verif_msg_cnt = PJ_ARRAY_SIZE(verif_msgs);
882 	pj_ssl_cert_get_verify_status_strings(ssl_sock_info->verify_status,
883 					      verif_msgs, &verif_msg_cnt);
884 	PJ_LOG(3,(THIS_FILE, "TLS cert verification result of %s : %s",
885 			     host_port,
886 			     (verif_msg_cnt == 1? verif_msgs[0]:"")));
887 	if (verif_msg_cnt > 1) {
888 	    unsigned i;
889 	    for (i = 0; i < verif_msg_cnt; ++i)
890 		PJ_LOG(3,(THIS_FILE, "- %s", verif_msgs[i]));
891 	}
892 
893 	if (ssl_sock_info->verify_status &&
894 	    !app_config.udp_cfg.tls_setting.verify_server)
895 	{
896 	    PJ_LOG(3,(THIS_FILE, "PJSUA is configured to ignore TLS cert "
897 				 "verification errors"));
898 	}
899     }
900 
901 #endif
902 
903 }
904 
905 /*
906  * Notification on ICE error.
907  */
on_ice_transport_error(int index,pj_ice_strans_op op,pj_status_t status,void * param)908 static void on_ice_transport_error(int index, pj_ice_strans_op op,
909 				   pj_status_t status, void *param)
910 {
911     PJ_UNUSED_ARG(op);
912     PJ_UNUSED_ARG(param);
913     PJ_PERROR(1,(THIS_FILE, status,
914 	         "ICE keep alive failure for transport %d", index));
915 }
916 
917 /*
918  * Notification on sound device operation.
919  */
on_snd_dev_operation(int operation)920 static pj_status_t on_snd_dev_operation(int operation)
921 {
922     int cap_dev, play_dev;
923 
924     pjsua_get_snd_dev(&cap_dev, &play_dev);
925     PJ_LOG(3,(THIS_FILE, "Turning sound device %d %d %s", cap_dev, play_dev,
926     	      (operation? "ON":"OFF")));
927     return PJ_SUCCESS;
928 }
929 
get_media_dir(pjmedia_dir dir)930 static char *get_media_dir(pjmedia_dir dir) {
931     switch (dir) {
932     case PJMEDIA_DIR_ENCODING:
933 	return "TX";
934     case PJMEDIA_DIR_DECODING:
935 	return "RX";
936     case PJMEDIA_DIR_ENCODING+PJMEDIA_DIR_DECODING:
937 	return "TX+RX";
938     default:
939 	return "unknown dir";
940     }
941 }
942 
943 /* Callback on media events */
on_call_media_event(pjsua_call_id call_id,unsigned med_idx,pjmedia_event * event)944 static void on_call_media_event(pjsua_call_id call_id,
945                                 unsigned med_idx,
946                                 pjmedia_event *event)
947 {
948     char event_name[5];
949 
950     PJ_LOG(5,(THIS_FILE, "Event %s",
951 	      pjmedia_fourcc_name(event->type, event_name)));
952 
953     if (event->type == PJMEDIA_EVENT_MEDIA_TP_ERR) {
954 	pjmedia_event_media_tp_err_data *err_data;
955 
956 	err_data = &event->data.med_tp_err;
957 	PJ_PERROR(3, (THIS_FILE, err_data->status,
958 		  "Media transport error event (%s %s %s)",
959 		  (err_data->type==PJMEDIA_TYPE_AUDIO)?"Audio":"Video",
960 		  (err_data->is_rtp)?"RTP":"RTCP",
961 		  get_media_dir(err_data->dir)));
962     }
963 #if PJSUA_HAS_VIDEO
964     else if (event->type == PJMEDIA_EVENT_FMT_CHANGED) {
965 	/* Adjust renderer window size to original video size */
966 	pjsua_call_info ci;
967 
968 	pjsua_call_get_info(call_id, &ci);
969 
970 	if ((ci.media[med_idx].type == PJMEDIA_TYPE_VIDEO) &&
971 	    (ci.media[med_idx].dir & PJMEDIA_DIR_DECODING))
972 	{
973 	    pjsua_vid_win_id wid;
974 	    pjmedia_rect_size size;
975 	    pjsua_vid_win_info win_info;
976 
977 	    wid = ci.media[med_idx].stream.vid.win_in;
978 	    pjsua_vid_win_get_info(wid, &win_info);
979 
980 	    size = event->data.fmt_changed.new_fmt.det.vid.size;
981 	    if (size.w != win_info.size.w || size.h != win_info.size.h) {
982 		pjsua_vid_win_set_size(wid, &size);
983 
984 		/* Re-arrange video windows */
985 		arrange_window(PJSUA_INVALID_ID);
986 	    }
987 	}
988     }
989 #else
990     PJ_UNUSED_ARG(call_id);
991     PJ_UNUSED_ARG(med_idx);
992 #endif
993 }
994 
995 #ifdef TRANSPORT_ADAPTER_SAMPLE
996 /*
997  * This callback is called when media transport needs to be created.
998  */
on_create_media_transport(pjsua_call_id call_id,unsigned media_idx,pjmedia_transport * base_tp,unsigned flags)999 static pjmedia_transport* on_create_media_transport(pjsua_call_id call_id,
1000 						    unsigned media_idx,
1001 						    pjmedia_transport *base_tp,
1002 						    unsigned flags)
1003 {
1004     pjmedia_transport *adapter;
1005     pj_status_t status;
1006 
1007     /* Create the adapter */
1008     status = pjmedia_tp_adapter_create(pjsua_get_pjmedia_endpt(),
1009                                        NULL, base_tp,
1010                                        (flags & PJSUA_MED_TP_CLOSE_MEMBER),
1011                                        &adapter);
1012     if (status != PJ_SUCCESS) {
1013 	PJ_PERROR(1,(THIS_FILE, status, "Error creating adapter"));
1014 	return NULL;
1015     }
1016 
1017     PJ_LOG(3,(THIS_FILE, "Media transport is created for call %d media %d",
1018 	      call_id, media_idx));
1019 
1020     return adapter;
1021 }
1022 #endif
1023 
1024 /* Playfile done notification, set timer to hangup calls */
on_playfile_done(pjmedia_port * port,void * usr_data)1025 void on_playfile_done(pjmedia_port *port, void *usr_data)
1026 {
1027     pj_time_val delay;
1028 
1029     PJ_UNUSED_ARG(port);
1030     PJ_UNUSED_ARG(usr_data);
1031 
1032     /* Just rewind WAV when it is played outside of call */
1033     if (pjsua_call_get_count() == 0) {
1034 	pjsua_player_set_pos(app_config.wav_id, 0);
1035     }
1036 
1037     /* Timer is already active */
1038     if (app_config.auto_hangup_timer.id == 1)
1039 	return;
1040 
1041     app_config.auto_hangup_timer.id = 1;
1042     delay.sec = 0;
1043     delay.msec = 200; /* Give 200 ms before hangup */
1044     pjsip_endpt_schedule_timer(pjsua_get_pjsip_endpt(),
1045 			       &app_config.auto_hangup_timer,
1046 			       &delay);
1047 }
1048 
1049 /* IP change progress callback. */
on_ip_change_progress(pjsua_ip_change_op op,pj_status_t status,const pjsua_ip_change_op_info * info)1050 void on_ip_change_progress(pjsua_ip_change_op op,
1051 			   pj_status_t status,
1052 			   const pjsua_ip_change_op_info *info)
1053 {
1054     char info_str[128];
1055     pjsua_acc_info acc_info;
1056     pjsua_transport_info tp_info;
1057 
1058     if (status == PJ_SUCCESS) {
1059 	switch (op) {
1060 	case PJSUA_IP_CHANGE_OP_RESTART_LIS:
1061 	    pjsua_transport_get_info(info->lis_restart.transport_id, &tp_info);
1062 	    pj_ansi_snprintf(info_str, sizeof(info_str),
1063 			     "restart transport %.*s",
1064 			     (int)tp_info.info.slen, tp_info.info.ptr);
1065 	    break;
1066 	case PJSUA_IP_CHANGE_OP_ACC_SHUTDOWN_TP:
1067 	    pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info);
1068 
1069 	    pj_ansi_snprintf(info_str, sizeof(info_str),
1070 			     "transport shutdown for account %.*s",
1071 			     (int)acc_info.acc_uri.slen,
1072 			     acc_info.acc_uri.ptr);
1073 	    break;
1074 	case PJSUA_IP_CHANGE_OP_ACC_UPDATE_CONTACT:
1075 	    pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info);
1076 	    if (info->acc_update_contact.code) {
1077 		pj_ansi_snprintf(info_str, sizeof(info_str),
1078 				 "update contact for account %.*s, code[%d]",
1079 				 (int)acc_info.acc_uri.slen,
1080 				 acc_info.acc_uri.ptr,
1081 				 info->acc_update_contact.code);
1082 	    } else {
1083 		pj_ansi_snprintf(info_str, sizeof(info_str),
1084 				 "update contact for account %.*s",
1085 				 (int)acc_info.acc_uri.slen,
1086 				 acc_info.acc_uri.ptr);
1087 	    }
1088 	    break;
1089 	case PJSUA_IP_CHANGE_OP_ACC_HANGUP_CALLS:
1090 	    pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info);
1091 	    pj_ansi_snprintf(info_str, sizeof(info_str),
1092 			     "hangup call for account %.*s, call_id[%d]",
1093 			     (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr,
1094 			     info->acc_hangup_calls.call_id);
1095 	    break;
1096 	case PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS:
1097 	    pjsua_acc_get_info(info->acc_shutdown_tp.acc_id, &acc_info);
1098 	    pj_ansi_snprintf(info_str, sizeof(info_str),
1099 			     "reinvite call for account %.*s, call_id[%d]",
1100 			     (int)acc_info.acc_uri.slen, acc_info.acc_uri.ptr,
1101 			     info->acc_reinvite_calls.call_id);
1102 	    break;
1103 	case PJSUA_IP_CHANGE_OP_COMPLETED:
1104 	    pj_ansi_snprintf(info_str, sizeof(info_str),
1105 			     "done");
1106 	default:
1107 	    break;
1108 	}
1109 	PJ_LOG(3,(THIS_FILE, "IP change progress report : %s", info_str));
1110 
1111     } else {
1112 	PJ_PERROR(3,(THIS_FILE, status, "IP change progress fail"));
1113     }
1114 }
1115 
1116 /* Auto hangup timer callback */
hangup_timeout_callback(pj_timer_heap_t * timer_heap,struct pj_timer_entry * entry)1117 static void hangup_timeout_callback(pj_timer_heap_t *timer_heap,
1118 				    struct pj_timer_entry *entry)
1119 {
1120     PJ_UNUSED_ARG(timer_heap);
1121     PJ_UNUSED_ARG(entry);
1122 
1123     app_config.auto_hangup_timer.id = 0;
1124     pjsua_call_hangup_all();
1125 }
1126 
1127 /*
1128  * A simple registrar, invoked by default_mod_on_rx_request()
1129  */
simple_registrar(pjsip_rx_data * rdata)1130 static void simple_registrar(pjsip_rx_data *rdata)
1131 {
1132     pjsip_tx_data *tdata;
1133     const pjsip_expires_hdr *exp;
1134     const pjsip_hdr *h;
1135     unsigned cnt = 0;
1136     pjsip_generic_string_hdr *srv;
1137     pj_status_t status;
1138 
1139     status = pjsip_endpt_create_response(pjsua_get_pjsip_endpt(),
1140 					 rdata, 200, NULL, &tdata);
1141     if (status != PJ_SUCCESS)
1142     return;
1143 
1144     exp = (pjsip_expires_hdr *)pjsip_msg_find_hdr(rdata->msg_info.msg,
1145 						  PJSIP_H_EXPIRES, NULL);
1146 
1147     h = rdata->msg_info.msg->hdr.next;
1148     while (h != &rdata->msg_info.msg->hdr) {
1149 	if (h->type == PJSIP_H_CONTACT) {
1150 	    const pjsip_contact_hdr *c = (const pjsip_contact_hdr*)h;
1151 	    unsigned e = c->expires;
1152 
1153 	    if (e != PJSIP_EXPIRES_NOT_SPECIFIED) {
1154 		if (exp)
1155 		    e = exp->ivalue;
1156 		else
1157 		    e = 3600;
1158 	    }
1159 
1160 	    if (e > 0) {
1161 		pjsip_contact_hdr *nc = (pjsip_contact_hdr *)pjsip_hdr_clone(
1162 								tdata->pool, h);
1163 		nc->expires = e;
1164 		pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)nc);
1165 		++cnt;
1166 	    }
1167 	}
1168 	h = h->next;
1169     }
1170 
1171     srv = pjsip_generic_string_hdr_create(tdata->pool, NULL, NULL);
1172     srv->name = pj_str("Server");
1173     srv->hvalue = pj_str("pjsua simple registrar");
1174     pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr*)srv);
1175 
1176     pjsip_endpt_send_response2(pjsua_get_pjsip_endpt(),
1177 		       rdata, tdata, NULL, NULL);
1178 }
1179 
1180 /*****************************************************************************
1181  * A simple module to handle otherwise unhandled request. We will register
1182  * this with the lowest priority.
1183  */
1184 
1185 /* Notification on incoming request */
default_mod_on_rx_request(pjsip_rx_data * rdata)1186 static pj_bool_t default_mod_on_rx_request(pjsip_rx_data *rdata)
1187 {
1188     pjsip_tx_data *tdata;
1189     pjsip_status_code status_code;
1190     pj_status_t status;
1191 
1192     /* Don't respond to ACK! */
1193     if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
1194 			 &pjsip_ack_method) == 0)
1195 	return PJ_TRUE;
1196 
1197     /* Simple registrar */
1198     if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
1199                          &pjsip_register_method) == 0)
1200     {
1201 	simple_registrar(rdata);
1202 	return PJ_TRUE;
1203     }
1204 
1205     /* Create basic response. */
1206     if (pjsip_method_cmp(&rdata->msg_info.msg->line.req.method,
1207 			 &pjsip_notify_method) == 0)
1208     {
1209 	/* Unsolicited NOTIFY's, send with Bad Request */
1210 	status_code = PJSIP_SC_BAD_REQUEST;
1211     } else {
1212 	/* Probably unknown method */
1213 	status_code = PJSIP_SC_METHOD_NOT_ALLOWED;
1214     }
1215     status = pjsip_endpt_create_response(pjsua_get_pjsip_endpt(),
1216 					 rdata, status_code,
1217 					 NULL, &tdata);
1218     if (status != PJ_SUCCESS) {
1219 	pjsua_perror(THIS_FILE, "Unable to create response", status);
1220 	return PJ_TRUE;
1221     }
1222 
1223     /* Add Allow if we're responding with 405 */
1224     if (status_code == PJSIP_SC_METHOD_NOT_ALLOWED) {
1225 	const pjsip_hdr *cap_hdr;
1226 	cap_hdr = pjsip_endpt_get_capability(pjsua_get_pjsip_endpt(),
1227 					     PJSIP_H_ALLOW, NULL);
1228 	if (cap_hdr) {
1229 	    pjsip_msg_add_hdr(tdata->msg, (pjsip_hdr *)pjsip_hdr_clone(
1230 							 tdata->pool, cap_hdr));
1231 	}
1232     }
1233 
1234     /* Add User-Agent header */
1235     {
1236 	pj_str_t user_agent;
1237 	char tmp[80];
1238 	const pj_str_t USER_AGENT = { "User-Agent", 10};
1239 	pjsip_hdr *h;
1240 
1241 	pj_ansi_snprintf(tmp, sizeof(tmp), "PJSUA v%s/%s",
1242 			 pj_get_version(), PJ_OS_NAME);
1243 	pj_strdup2_with_null(tdata->pool, &user_agent, tmp);
1244 
1245 	h = (pjsip_hdr*) pjsip_generic_string_hdr_create(tdata->pool,
1246 							 &USER_AGENT,
1247 							 &user_agent);
1248 	pjsip_msg_add_hdr(tdata->msg, h);
1249     }
1250 
1251     pjsip_endpt_send_response2(pjsua_get_pjsip_endpt(), rdata, tdata,
1252 			       NULL, NULL);
1253 
1254     return PJ_TRUE;
1255 }
1256 
1257 /* The module instance. */
1258 static pjsip_module mod_default_handler =
1259 {
1260     NULL, NULL,				/* prev, next.		*/
1261     { "mod-default-handler", 19 },	/* Name.		*/
1262     -1,					/* Id			*/
1263     PJSIP_MOD_PRIORITY_APPLICATION+99,	/* Priority	        */
1264     NULL,				/* load()		*/
1265     NULL,				/* start()		*/
1266     NULL,				/* stop()		*/
1267     NULL,				/* unload()		*/
1268     &default_mod_on_rx_request,		/* on_rx_request()	*/
1269     NULL,				/* on_rx_response()	*/
1270     NULL,				/* on_tx_request.	*/
1271     NULL,				/* on_tx_response()	*/
1272     NULL,				/* on_tsx_state()	*/
1273 
1274 };
1275 
1276 /** CLI callback **/
1277 
1278 /* Called on CLI (re)started, e.g: initial start, after iOS bg */
cli_on_started(pj_status_t status)1279 void cli_on_started(pj_status_t status)
1280 {
1281     /* Notify app */
1282     if (app_cfg.on_started) {
1283 	if (status == PJ_SUCCESS) {
1284 	    char info[128];
1285 	    cli_get_info(info, sizeof(info));
1286 	    if (app_cfg.on_started) {
1287 		(*app_cfg.on_started)(status, info);
1288 	    }
1289 	} else {
1290 	    if (app_cfg.on_started) {
1291 		(*app_cfg.on_started)(status, NULL);
1292 	    }
1293 	}
1294     }
1295 }
1296 
1297 /* Called on CLI quit */
cli_on_stopped(pj_bool_t restart,int argc,char * argv[])1298 void cli_on_stopped(pj_bool_t restart, int argc, char* argv[])
1299 {
1300     /* Notify app */
1301     if (app_cfg.on_stopped)
1302 	(*app_cfg.on_stopped)(restart, argc, argv);
1303 }
1304 
1305 
1306 /* Called on pjsua legacy quit */
legacy_on_stopped(pj_bool_t restart)1307 void legacy_on_stopped(pj_bool_t restart)
1308 {
1309     /* Notify app */
1310     if (app_cfg.on_stopped)
1311 	(*app_cfg.on_stopped)(restart, 1, NULL);
1312 }
1313 
1314 /*****************************************************************************
1315  * Public API
1316  */
1317 
stdout_refresh_proc(void * arg)1318 int stdout_refresh_proc(void *arg)
1319 {
1320     extern char *stdout_refresh_text;
1321 
1322     PJ_UNUSED_ARG(arg);
1323 
1324     /* Set thread to lowest priority so that it doesn't clobber
1325      * stdout output
1326      */
1327     pj_thread_set_prio(pj_thread_this(),
1328 		       pj_thread_get_prio_min(pj_thread_this()));
1329 
1330     while (!stdout_refresh_quit) {
1331 	pj_thread_sleep(stdout_refresh * 1000);
1332 	puts(stdout_refresh_text);
1333 	fflush(stdout);
1334     }
1335 
1336     return 0;
1337 }
1338 
1339 
app_init(void)1340 static pj_status_t app_init(void)
1341 {
1342     pjsua_transport_id transport_id = -1;
1343     pjsua_transport_config tcp_cfg;
1344     unsigned i;
1345     pj_pool_t *tmp_pool;
1346     pj_status_t status;
1347 
1348     /** Create pjsua **/
1349     status = pjsua_create();
1350     if (status != PJ_SUCCESS)
1351 	return status;
1352 
1353     /* Create pool for application */
1354     app_config.pool = pjsua_pool_create("pjsua-app", 1000, 1000);
1355     tmp_pool = pjsua_pool_create("tmp-pjsua", 1000, 1000);;
1356 
1357     /* Init CLI & its FE settings */
1358     if (!app_running) {
1359 	pj_cli_cfg_default(&app_config.cli_cfg.cfg);
1360 	pj_cli_telnet_cfg_default(&app_config.cli_cfg.telnet_cfg);
1361 	pj_cli_console_cfg_default(&app_config.cli_cfg.console_cfg);
1362 	app_config.cli_cfg.telnet_cfg.on_started = cli_on_started;
1363     }
1364 
1365     /** Parse args **/
1366     status = load_config(app_cfg.argc, app_cfg.argv, &uri_arg);
1367     if (status != PJ_SUCCESS) {
1368 	pj_pool_release(tmp_pool);
1369 	return status;
1370     }
1371 
1372     /* Initialize application callbacks */
1373     app_config.cfg.cb.on_call_state = &on_call_state;
1374     app_config.cfg.cb.on_stream_destroyed = &on_stream_destroyed;
1375     app_config.cfg.cb.on_call_media_state = &on_call_media_state;
1376     app_config.cfg.cb.on_incoming_call = &on_incoming_call;
1377     app_config.cfg.cb.on_dtmf_digit2 = &call_on_dtmf_callback2;
1378     app_config.cfg.cb.on_call_redirected = &call_on_redirected;
1379     app_config.cfg.cb.on_reg_state = &on_reg_state;
1380     app_config.cfg.cb.on_incoming_subscribe = &on_incoming_subscribe;
1381     app_config.cfg.cb.on_buddy_state = &on_buddy_state;
1382     app_config.cfg.cb.on_buddy_evsub_state = &on_buddy_evsub_state;
1383     app_config.cfg.cb.on_pager = &on_pager;
1384     app_config.cfg.cb.on_typing = &on_typing;
1385     app_config.cfg.cb.on_call_transfer_status = &on_call_transfer_status;
1386     app_config.cfg.cb.on_call_replaced = &on_call_replaced;
1387     app_config.cfg.cb.on_nat_detect = &on_nat_detect;
1388     app_config.cfg.cb.on_mwi_info = &on_mwi_info;
1389     app_config.cfg.cb.on_transport_state = &on_transport_state;
1390     app_config.cfg.cb.on_ice_transport_error = &on_ice_transport_error;
1391     app_config.cfg.cb.on_snd_dev_operation = &on_snd_dev_operation;
1392     app_config.cfg.cb.on_call_media_event = &on_call_media_event;
1393     app_config.cfg.cb.on_ip_change_progress = &on_ip_change_progress;
1394 #ifdef TRANSPORT_ADAPTER_SAMPLE
1395     app_config.cfg.cb.on_create_media_transport = &on_create_media_transport;
1396 #endif
1397 
1398     /* Set sound device latency */
1399     if (app_config.capture_lat > 0)
1400 	app_config.media_cfg.snd_rec_latency = app_config.capture_lat;
1401     if (app_config.playback_lat)
1402 	app_config.media_cfg.snd_play_latency = app_config.playback_lat;
1403 
1404     if (app_cfg.on_config_init)
1405 	(*app_cfg.on_config_init)(&app_config);
1406 
1407     /* Initialize pjsua */
1408     status = pjsua_init(&app_config.cfg, &app_config.log_cfg,
1409 			&app_config.media_cfg);
1410     if (status != PJ_SUCCESS) {
1411 	pj_pool_release(tmp_pool);
1412 	return status;
1413     }
1414 
1415     /* Initialize our module to handle otherwise unhandled request */
1416     status = pjsip_endpt_register_module(pjsua_get_pjsip_endpt(),
1417 					 &mod_default_handler);
1418     if (status != PJ_SUCCESS)
1419 	return status;
1420 
1421 #ifdef STEREO_DEMO
1422     stereo_demo();
1423 #endif
1424 
1425     /* Initialize calls data */
1426     for (i=0; i<PJ_ARRAY_SIZE(app_config.call_data); ++i) {
1427 	app_config.call_data[i].timer.id = PJSUA_INVALID_ID;
1428 	app_config.call_data[i].timer.cb = &call_timeout_callback;
1429     }
1430 
1431     /* Optionally registers WAV file */
1432     for (i=0; i<app_config.wav_count; ++i) {
1433 	pjsua_player_id wav_id;
1434 	unsigned play_options = 0;
1435 
1436 	if (app_config.auto_play_hangup)
1437 	    play_options |= PJMEDIA_FILE_NO_LOOP;
1438 
1439 	status = pjsua_player_create(&app_config.wav_files[i], play_options,
1440 				     &wav_id);
1441 	if (status != PJ_SUCCESS)
1442 	    goto on_error;
1443 
1444 	if (app_config.wav_id == PJSUA_INVALID_ID) {
1445 	    app_config.wav_id = wav_id;
1446 	    app_config.wav_port = pjsua_player_get_conf_port(app_config.wav_id);
1447 	    if (app_config.auto_play_hangup) {
1448 		pjmedia_port *port;
1449 
1450 		pjsua_player_get_port(app_config.wav_id, &port);
1451 		status = pjmedia_wav_player_set_eof_cb2(port, NULL,
1452 						        &on_playfile_done);
1453 		if (status != PJ_SUCCESS)
1454 		    goto on_error;
1455 
1456 		pj_timer_entry_init(&app_config.auto_hangup_timer, 0, NULL,
1457 				    &hangup_timeout_callback);
1458 	    }
1459 	}
1460     }
1461 
1462     /* Optionally registers tone players */
1463     for (i=0; i<app_config.tone_count; ++i) {
1464 	pjmedia_port *tport;
1465 	char name[80];
1466 	pj_str_t label;
1467 	pj_status_t status2;
1468 
1469 	pj_ansi_snprintf(name, sizeof(name), "tone-%d,%d",
1470 			 app_config.tones[i].freq1,
1471 			 app_config.tones[i].freq2);
1472 	label = pj_str(name);
1473 	status2 = pjmedia_tonegen_create2(app_config.pool, &label,
1474 					  8000, 1, 160, 16,
1475 					  PJMEDIA_TONEGEN_LOOP,  &tport);
1476 	if (status2 != PJ_SUCCESS) {
1477 	    pjsua_perror(THIS_FILE, "Unable to create tone generator", status);
1478 	    goto on_error;
1479 	}
1480 
1481 	status2 = pjsua_conf_add_port(app_config.pool, tport,
1482 				     &app_config.tone_slots[i]);
1483 	pj_assert(status2 == PJ_SUCCESS);
1484 
1485 	status2 = pjmedia_tonegen_play(tport, 1, &app_config.tones[i], 0);
1486 	pj_assert(status2 == PJ_SUCCESS);
1487     }
1488 
1489     /* Optionally create recorder file, if any. */
1490     if (app_config.rec_file.slen) {
1491 	status = pjsua_recorder_create(&app_config.rec_file, 0, NULL, 0, 0,
1492 				       &app_config.rec_id);
1493 	if (status != PJ_SUCCESS)
1494 	    goto on_error;
1495 
1496 	app_config.rec_port = pjsua_recorder_get_conf_port(app_config.rec_id);
1497     }
1498 
1499     pj_memcpy(&tcp_cfg, &app_config.udp_cfg, sizeof(tcp_cfg));
1500 
1501     /* Create ringback tones */
1502     if (app_config.no_tones == PJ_FALSE) {
1503 	unsigned samples_per_frame;
1504 	pjmedia_tone_desc tone[RING_CNT+RINGBACK_CNT];
1505 	pj_str_t name;
1506 
1507 	samples_per_frame = app_config.media_cfg.audio_frame_ptime *
1508 			    app_config.media_cfg.clock_rate *
1509 			    app_config.media_cfg.channel_count / 1000;
1510 
1511 	/* Ringback tone (call is ringing) */
1512 	name = pj_str("ringback");
1513 	status = pjmedia_tonegen_create2(app_config.pool, &name,
1514 					 app_config.media_cfg.clock_rate,
1515 					 app_config.media_cfg.channel_count,
1516 					 samples_per_frame,
1517 					 16, PJMEDIA_TONEGEN_LOOP,
1518 					 &app_config.ringback_port);
1519 	if (status != PJ_SUCCESS)
1520 	    goto on_error;
1521 
1522 	pj_bzero(&tone, sizeof(tone));
1523 	for (i=0; i<RINGBACK_CNT; ++i) {
1524 	    tone[i].freq1 = RINGBACK_FREQ1;
1525 	    tone[i].freq2 = RINGBACK_FREQ2;
1526 	    tone[i].on_msec = RINGBACK_ON;
1527 	    tone[i].off_msec = RINGBACK_OFF;
1528 	}
1529 	tone[RINGBACK_CNT-1].off_msec = RINGBACK_INTERVAL;
1530 
1531 	pjmedia_tonegen_play(app_config.ringback_port, RINGBACK_CNT, tone,
1532 			     PJMEDIA_TONEGEN_LOOP);
1533 
1534 
1535 	status = pjsua_conf_add_port(app_config.pool, app_config.ringback_port,
1536 				     &app_config.ringback_slot);
1537 	if (status != PJ_SUCCESS)
1538 	    goto on_error;
1539 
1540 	/* Ring (to alert incoming call) */
1541 	name = pj_str("ring");
1542 	status = pjmedia_tonegen_create2(app_config.pool, &name,
1543 					 app_config.media_cfg.clock_rate,
1544 					 app_config.media_cfg.channel_count,
1545 					 samples_per_frame,
1546 					 16, PJMEDIA_TONEGEN_LOOP,
1547 					 &app_config.ring_port);
1548 	if (status != PJ_SUCCESS)
1549 	    goto on_error;
1550 
1551 	for (i=0; i<RING_CNT; ++i) {
1552 	    tone[i].freq1 = RING_FREQ1;
1553 	    tone[i].freq2 = RING_FREQ2;
1554 	    tone[i].on_msec = RING_ON;
1555 	    tone[i].off_msec = RING_OFF;
1556 	}
1557 	tone[RING_CNT-1].off_msec = RING_INTERVAL;
1558 
1559 	pjmedia_tonegen_play(app_config.ring_port, RING_CNT,
1560 			     tone, PJMEDIA_TONEGEN_LOOP);
1561 
1562 	status = pjsua_conf_add_port(app_config.pool, app_config.ring_port,
1563 				     &app_config.ring_slot);
1564 	if (status != PJ_SUCCESS)
1565 	    goto on_error;
1566 
1567     }
1568 
1569     /* Create AVI player virtual devices */
1570     if (app_config.avi_cnt) {
1571 #if PJMEDIA_HAS_VIDEO && PJMEDIA_VIDEO_DEV_HAS_AVI
1572 	pjmedia_vid_dev_factory *avi_factory;
1573 
1574 	status = pjmedia_avi_dev_create_factory(pjsua_get_pool_factory(),
1575 	                                        app_config.avi_cnt,
1576 	                                        &avi_factory);
1577 	if (status != PJ_SUCCESS) {
1578 	    PJ_PERROR(1,(THIS_FILE, status, "Error creating AVI factory"));
1579 	    goto on_error;
1580 	}
1581 
1582 	for (i=0; i<app_config.avi_cnt; ++i) {
1583 	    pjmedia_avi_dev_param avdp;
1584 	    pjmedia_vid_dev_index avid;
1585 	    unsigned strm_idx, strm_cnt;
1586 
1587 	    app_config.avi[i].dev_id = PJMEDIA_VID_INVALID_DEV;
1588 	    app_config.avi[i].slot = PJSUA_INVALID_ID;
1589 
1590 	    pjmedia_avi_dev_param_default(&avdp);
1591 	    avdp.path = app_config.avi[i].path;
1592 
1593 	    status =  pjmedia_avi_dev_alloc(avi_factory, &avdp, &avid);
1594 	    if (status != PJ_SUCCESS) {
1595 		PJ_PERROR(1,(THIS_FILE, status,
1596 			     "Error creating AVI player for %.*s",
1597 			     (int)avdp.path.slen, avdp.path.ptr));
1598 		goto on_error;
1599 	    }
1600 
1601 	    PJ_LOG(4,(THIS_FILE, "AVI player %.*s created, dev_id=%d",
1602 		      (int)avdp.title.slen, avdp.title.ptr, avid));
1603 
1604 	    app_config.avi[i].dev_id = avid;
1605 	    if (app_config.avi_def_idx == PJSUA_INVALID_ID)
1606 		app_config.avi_def_idx = i;
1607 
1608 	    strm_cnt = pjmedia_avi_streams_get_num_streams(avdp.avi_streams);
1609 	    for (strm_idx=0; strm_idx<strm_cnt; ++strm_idx) {
1610 		pjmedia_port *aud;
1611 		pjmedia_format *fmt;
1612 		pjsua_conf_port_id slot;
1613 		char fmt_name[5];
1614 
1615 		aud = pjmedia_avi_streams_get_stream(avdp.avi_streams,
1616 		                                     strm_idx);
1617 		fmt = &aud->info.fmt;
1618 
1619 		pjmedia_fourcc_name(fmt->id, fmt_name);
1620 
1621 		if (fmt->id == PJMEDIA_FORMAT_PCM) {
1622 		    status = pjsua_conf_add_port(app_config.pool, aud,
1623 		                                 &slot);
1624 		    if (status == PJ_SUCCESS) {
1625 			PJ_LOG(4,(THIS_FILE,
1626 				  "AVI %.*s: audio added to slot %d",
1627 				  (int)avdp.title.slen, avdp.title.ptr,
1628 				  slot));
1629 			app_config.avi[i].slot = slot;
1630 		    }
1631 		} else {
1632 		    PJ_LOG(4,(THIS_FILE,
1633 			      "AVI %.*s: audio ignored, format=%s",
1634 			      (int)avdp.title.slen, avdp.title.ptr,
1635 			      fmt_name));
1636 		}
1637 	    }
1638 	}
1639 #else
1640 	PJ_LOG(2,(THIS_FILE,
1641 		  "Warning: --play-avi is ignored because AVI is disabled"));
1642 #endif	/* PJMEDIA_VIDEO_DEV_HAS_AVI */
1643     }
1644 
1645     /* Add UDP transport unless it's disabled. */
1646     if (!app_config.no_udp) {
1647 	pjsua_acc_id aid;
1648 	pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP;
1649 
1650 	status = pjsua_transport_create(type,
1651 					&app_config.udp_cfg,
1652 					&transport_id);
1653 	if (status != PJ_SUCCESS)
1654 	    goto on_error;
1655 
1656 	/* Add local account */
1657 	pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);
1658 
1659 	/* Adjust local account config based on pjsua app config */
1660 	{
1661 	    pjsua_acc_config acc_cfg;
1662 	    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);
1663 
1664 	    app_config_init_video(&acc_cfg);
1665 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1666 	    pjsua_acc_modify(aid, &acc_cfg);
1667 	}
1668 
1669 	//pjsua_acc_set_transport(aid, transport_id);
1670 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1671 
1672 	if (app_config.udp_cfg.port == 0) {
1673 	    pjsua_transport_info ti;
1674 	    pj_sockaddr_in *a;
1675 
1676 	    pjsua_transport_get_info(transport_id, &ti);
1677 	    a = (pj_sockaddr_in*)&ti.local_addr;
1678 
1679 	    tcp_cfg.port = pj_ntohs(a->sin_port);
1680 	}
1681     }
1682 
1683     /* Add UDP IPv6 transport unless it's disabled. */
1684     if (!app_config.no_udp && app_config.ipv6) {
1685 	pjsua_acc_id aid;
1686 	pjsip_transport_type_e type = PJSIP_TRANSPORT_UDP6;
1687 	pjsua_transport_config udp_cfg;
1688 
1689 	udp_cfg = app_config.udp_cfg;
1690 	if (udp_cfg.port == 0)
1691 	    udp_cfg.port = 5060;
1692 	else
1693 	    udp_cfg.port += 10;
1694 	status = pjsua_transport_create(type,
1695 					&udp_cfg,
1696 					&transport_id);
1697 	if (status != PJ_SUCCESS)
1698 	    goto on_error;
1699 
1700 	/* Add local account */
1701 	pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);
1702 
1703 	/* Adjust local account config based on pjsua app config */
1704 	{
1705 	    pjsua_acc_config acc_cfg;
1706 	    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);
1707 
1708 	    app_config_init_video(&acc_cfg);
1709 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1710 	    acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED;
1711 	    pjsua_acc_modify(aid, &acc_cfg);
1712 	}
1713 
1714 	//pjsua_acc_set_transport(aid, transport_id);
1715 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1716 
1717 	if (app_config.udp_cfg.port == 0) {
1718 	    pjsua_transport_info ti;
1719 
1720 	    pjsua_transport_get_info(transport_id, &ti);
1721 	    tcp_cfg.port = pj_sockaddr_get_port(&ti.local_addr);
1722 	}
1723     }
1724 
1725     /* Add TCP transport unless it's disabled */
1726     if (!app_config.no_tcp) {
1727 	pjsua_acc_id aid;
1728 
1729 	status = pjsua_transport_create(PJSIP_TRANSPORT_TCP,
1730 					&tcp_cfg,
1731 					&transport_id);
1732 	if (status != PJ_SUCCESS)
1733 	    goto on_error;
1734 
1735 	/* Add local account */
1736 	pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);
1737 
1738 	/* Adjust local account config based on pjsua app config */
1739 	{
1740 	    pjsua_acc_config acc_cfg;
1741 	    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);
1742 
1743 	    app_config_init_video(&acc_cfg);
1744 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1745 	    pjsua_acc_modify(aid, &acc_cfg);
1746 	}
1747 
1748 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1749 
1750     }
1751 
1752     /* Add TCP IPv6 transport unless it's disabled. */
1753     if (!app_config.no_tcp && app_config.ipv6) {
1754 	pjsua_acc_id aid;
1755 	pjsip_transport_type_e type = PJSIP_TRANSPORT_TCP6;
1756 
1757 	tcp_cfg.port += 10;
1758 
1759 	status = pjsua_transport_create(type,
1760 					&tcp_cfg,
1761 					&transport_id);
1762 	if (status != PJ_SUCCESS)
1763 	    goto on_error;
1764 
1765 	/* Add local account */
1766 	pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);
1767 
1768 	/* Adjust local account config based on pjsua app config */
1769 	{
1770 	    pjsua_acc_config acc_cfg;
1771 	    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);
1772 
1773 	    app_config_init_video(&acc_cfg);
1774 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1775 	    acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED;
1776 	    pjsua_acc_modify(aid, &acc_cfg);
1777 	}
1778 
1779 	//pjsua_acc_set_transport(aid, transport_id);
1780 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1781     }
1782 
1783 
1784 #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
1785     /* Add TLS transport when application wants one */
1786     if (app_config.use_tls) {
1787 
1788 	pjsua_acc_id acc_id;
1789 
1790 	/* Copy the QoS settings */
1791 	tcp_cfg.tls_setting.qos_type = tcp_cfg.qos_type;
1792 	pj_memcpy(&tcp_cfg.tls_setting.qos_params, &tcp_cfg.qos_params,
1793 		  sizeof(tcp_cfg.qos_params));
1794 
1795 	/* Set TLS port as TCP port+1 */
1796 	tcp_cfg.port++;
1797 	status = pjsua_transport_create(PJSIP_TRANSPORT_TLS,
1798 					&tcp_cfg,
1799 					&transport_id);
1800 	tcp_cfg.port--;
1801 	if (status != PJ_SUCCESS)
1802 	    goto on_error;
1803 
1804 	/* Add local account */
1805 	pjsua_acc_add_local(transport_id, PJ_FALSE, &acc_id);
1806 
1807 	/* Adjust local account config based on pjsua app config */
1808 	{
1809 	    pjsua_acc_config acc_cfg;
1810 	    pjsua_acc_get_config(acc_id, tmp_pool, &acc_cfg);
1811 
1812 	    app_config_init_video(&acc_cfg);
1813 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1814 	    pjsua_acc_modify(acc_id, &acc_cfg);
1815 	}
1816 
1817 	pjsua_acc_set_online_status(acc_id, PJ_TRUE);
1818     }
1819 
1820     /* Add TLS IPv6 transport unless it's disabled. */
1821     if (app_config.use_tls && app_config.ipv6) {
1822 	pjsua_acc_id aid;
1823 	pjsip_transport_type_e type = PJSIP_TRANSPORT_TLS6;
1824 
1825 	tcp_cfg.port += 10;
1826 
1827 	status = pjsua_transport_create(type,
1828 					&tcp_cfg,
1829 					&transport_id);
1830 	if (status != PJ_SUCCESS)
1831 	    goto on_error;
1832 
1833 	/* Add local account */
1834 	pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);
1835 
1836 	/* Adjust local account config based on pjsua app config */
1837 	{
1838 	    pjsua_acc_config acc_cfg;
1839 	    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);
1840 
1841 	    app_config_init_video(&acc_cfg);
1842 	    acc_cfg.rtp_cfg = app_config.rtp_cfg;
1843 	    acc_cfg.ipv6_media_use = PJSUA_IPV6_ENABLED;
1844 	    pjsua_acc_modify(aid, &acc_cfg);
1845 	}
1846 
1847 	//pjsua_acc_set_transport(aid, transport_id);
1848 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1849     }
1850 
1851 #endif
1852 
1853     if (transport_id == -1) {
1854 	PJ_LOG(1,(THIS_FILE, "Error: no transport is configured"));
1855 	status = -1;
1856 	goto on_error;
1857     }
1858 
1859 
1860     /* Add accounts */
1861     for (i=0; i<app_config.acc_cnt; ++i) {
1862 	app_config.acc_cfg[i].rtp_cfg = app_config.rtp_cfg;
1863 	app_config.acc_cfg[i].reg_retry_interval = 300;
1864 	app_config.acc_cfg[i].reg_first_retry_interval = 60;
1865 
1866 	app_config_init_video(&app_config.acc_cfg[i]);
1867 
1868 	status = pjsua_acc_add(&app_config.acc_cfg[i], PJ_TRUE, NULL);
1869 	if (status != PJ_SUCCESS)
1870 	    goto on_error;
1871 	pjsua_acc_set_online_status(current_acc, PJ_TRUE);
1872     }
1873 
1874     /* Add buddies */
1875     for (i=0; i<app_config.buddy_cnt; ++i) {
1876 	status = pjsua_buddy_add(&app_config.buddy_cfg[i], NULL);
1877 	if (status != PJ_SUCCESS) {
1878 	    PJ_PERROR(1,(THIS_FILE, status, "Error adding buddy"));
1879 	    goto on_error;
1880 	}
1881     }
1882 
1883     /* Optionally disable some codec */
1884     for (i=0; i<app_config.codec_dis_cnt; ++i) {
1885 	pjsua_codec_set_priority(&app_config.codec_dis[i],
1886 				 PJMEDIA_CODEC_PRIO_DISABLED);
1887 #if PJSUA_HAS_VIDEO
1888 	pjsua_vid_codec_set_priority(&app_config.codec_dis[i],
1889 				     PJMEDIA_CODEC_PRIO_DISABLED);
1890 #endif
1891     }
1892 
1893     /* Optionally set codec orders */
1894     for (i=0; i<app_config.codec_cnt; ++i) {
1895 	pjsua_codec_set_priority(&app_config.codec_arg[i],
1896 				 (pj_uint8_t)(PJMEDIA_CODEC_PRIO_NORMAL+i+9));
1897 #if PJSUA_HAS_VIDEO
1898 	pjsua_vid_codec_set_priority(&app_config.codec_arg[i],
1899 				   (pj_uint8_t)(PJMEDIA_CODEC_PRIO_NORMAL+i+9));
1900 #endif
1901     }
1902 
1903     /* Use null sound device? */
1904 #ifndef STEREO_DEMO
1905     if (app_config.null_audio) {
1906 	status = pjsua_set_null_snd_dev();
1907 	if (status != PJ_SUCCESS)
1908 	    goto on_error;
1909     }
1910 #endif
1911 
1912     if (app_config.capture_dev  != PJSUA_INVALID_ID ||
1913         app_config.playback_dev != PJSUA_INVALID_ID)
1914     {
1915 	status = pjsua_set_snd_dev(app_config.capture_dev,
1916 				   app_config.playback_dev);
1917 	if (status != PJ_SUCCESS)
1918 	    goto on_error;
1919     }
1920 
1921     /* Init call setting */
1922     pjsua_call_setting_default(&call_opt);
1923     call_opt.aud_cnt = app_config.aud_cnt;
1924     call_opt.vid_cnt = app_config.vid.vid_cnt;
1925 
1926 #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
1927     /* Wipe out TLS key settings in transport configs */
1928     pjsip_tls_setting_wipe_keys(&app_config.udp_cfg.tls_setting);
1929 #endif
1930 
1931     pj_pool_release(tmp_pool);
1932     return PJ_SUCCESS;
1933 
1934 on_error:
1935     pj_pool_release(tmp_pool);
1936     app_destroy();
1937     return status;
1938 }
1939 
pjsua_app_init(const pjsua_app_cfg_t * cfg)1940 pj_status_t pjsua_app_init(const pjsua_app_cfg_t *cfg)
1941 {
1942     pj_status_t status;
1943     pj_memcpy(&app_cfg, cfg, sizeof(app_cfg));
1944 
1945     status = app_init();
1946     if (status != PJ_SUCCESS)
1947 	return status;
1948 
1949     /* Init CLI if configured */
1950     if (app_config.use_cli) {
1951 	status = cli_init();
1952     }
1953     return status;
1954 }
1955 
pjsua_app_run(pj_bool_t wait_telnet_cli)1956 pj_status_t pjsua_app_run(pj_bool_t wait_telnet_cli)
1957 {
1958     pj_thread_t *stdout_refresh_thread = NULL;
1959     pj_status_t status;
1960 
1961     /* Start console refresh thread */
1962     if (stdout_refresh > 0) {
1963 	pj_thread_create(app_config.pool, "stdout", &stdout_refresh_proc,
1964 			 NULL, 0, 0, &stdout_refresh_thread);
1965     }
1966 
1967     status = pjsua_start();
1968     if (status != PJ_SUCCESS)
1969 	goto on_return;
1970 
1971     if (app_config.use_cli && (app_config.cli_cfg.cli_fe & CLI_FE_TELNET)) {
1972 	char info[128];
1973 	cli_get_info(info, sizeof(info));
1974 	if (app_cfg.on_started) {
1975 	    (*app_cfg.on_started)(status, info);
1976 	}
1977     } else {
1978 	if (app_cfg.on_started) {
1979 	    (*app_cfg.on_started)(status, "Ready");
1980 	}
1981     }
1982 
1983     /* If user specifies URI to call, then call the URI */
1984     if (uri_arg.slen) {
1985 	pjsua_call_setting_default(&call_opt);
1986 	call_opt.aud_cnt = app_config.aud_cnt;
1987 	call_opt.vid_cnt = app_config.vid.vid_cnt;
1988 
1989 	pjsua_call_make_call(current_acc, &uri_arg, &call_opt, NULL,
1990 			     NULL, NULL);
1991     }
1992 
1993     app_running = PJ_TRUE;
1994 
1995     if (app_config.use_cli)
1996 	cli_main(wait_telnet_cli);
1997     else
1998 	legacy_main();
1999 
2000     status = PJ_SUCCESS;
2001 
2002 on_return:
2003     if (stdout_refresh_thread) {
2004 	stdout_refresh_quit = PJ_TRUE;
2005 	pj_thread_join(stdout_refresh_thread);
2006 	pj_thread_destroy(stdout_refresh_thread);
2007 	stdout_refresh_quit = PJ_FALSE;
2008     }
2009     return status;
2010 }
2011 
app_destroy(void)2012 static pj_status_t app_destroy(void)
2013 {
2014     pj_status_t status = PJ_SUCCESS;
2015     unsigned i;
2016     pj_bool_t use_cli = PJ_FALSE;
2017     int cli_fe = 0;
2018     pj_uint16_t cli_telnet_port = 0;
2019 
2020 #ifdef STEREO_DEMO
2021     if (app_config.snd) {
2022 	pjmedia_snd_port_destroy(app_config.snd);
2023 	app_config.snd = NULL;
2024     }
2025     if (app_config.sc_ch1) {
2026 	pjsua_conf_remove_port(app_config.sc_ch1_slot);
2027 	app_config.sc_ch1_slot = PJSUA_INVALID_ID;
2028 	pjmedia_port_destroy(app_config.sc_ch1);
2029 	app_config.sc_ch1 = NULL;
2030     }
2031     if (app_config.sc) {
2032 	pjmedia_port_destroy(app_config.sc);
2033 	app_config.sc = NULL;
2034     }
2035 #endif
2036 
2037     /* Close avi devs and ports */
2038     for (i=0; i<app_config.avi_cnt; ++i) {
2039 	if (app_config.avi[i].slot != PJSUA_INVALID_ID)
2040 	    pjsua_conf_remove_port(app_config.avi[i].slot);
2041 #if PJMEDIA_HAS_VIDEO && PJMEDIA_VIDEO_DEV_HAS_AVI
2042 	if (app_config.avi[i].dev_id != PJMEDIA_VID_INVALID_DEV)
2043 	    pjmedia_avi_dev_free(app_config.avi[i].dev_id);
2044 #endif
2045     }
2046 
2047     /* Close ringback port */
2048     if (app_config.ringback_port &&
2049 	app_config.ringback_slot != PJSUA_INVALID_ID)
2050     {
2051 	pjsua_conf_remove_port(app_config.ringback_slot);
2052 	app_config.ringback_slot = PJSUA_INVALID_ID;
2053 	pjmedia_port_destroy(app_config.ringback_port);
2054 	app_config.ringback_port = NULL;
2055     }
2056 
2057     /* Close ring port */
2058     if (app_config.ring_port && app_config.ring_slot != PJSUA_INVALID_ID) {
2059 	pjsua_conf_remove_port(app_config.ring_slot);
2060 	app_config.ring_slot = PJSUA_INVALID_ID;
2061 	pjmedia_port_destroy(app_config.ring_port);
2062 	app_config.ring_port = NULL;
2063     }
2064 
2065     /* Close tone generators */
2066     for (i=0; i<app_config.tone_count; ++i) {
2067 	pjsua_conf_remove_port(app_config.tone_slots[i]);
2068     }
2069 
2070     pj_pool_safe_release(&app_config.pool);
2071 
2072     status = pjsua_destroy();
2073 
2074     if (app_config.use_cli) {
2075 	use_cli = app_config.use_cli;
2076 	cli_fe = app_config.cli_cfg.cli_fe;
2077 	cli_telnet_port = app_config.cli_cfg.telnet_cfg.port;
2078     }
2079 
2080 #if defined(PJSIP_HAS_TLS_TRANSPORT) && PJSIP_HAS_TLS_TRANSPORT!=0
2081     /* Wipe out TLS key settings in transport configs */
2082     pjsip_tls_setting_wipe_keys(&app_config.udp_cfg.tls_setting);
2083 #endif
2084 
2085     /* Reset config */
2086     pj_bzero(&app_config, sizeof(app_config));
2087 
2088     if (use_cli) {
2089 	app_config.use_cli = use_cli;
2090 	app_config.cli_cfg.cli_fe = cli_fe;
2091 	app_config.cli_cfg.telnet_cfg.port = cli_telnet_port;
2092     }
2093 
2094     return status;
2095 }
2096 
pjsua_app_destroy(void)2097 pj_status_t pjsua_app_destroy(void)
2098 {
2099     pj_status_t status;
2100 
2101     status = app_destroy();
2102 
2103     if (app_config.use_cli) {
2104 	cli_destroy();
2105     }
2106 
2107     return status;
2108 }
2109 
2110 /** ======================= **/
2111 
2112 #ifdef STEREO_DEMO
2113 /*
2114  * In this stereo demo, we open the sound device in stereo mode and
2115  * arrange the attachment to the PJSUA-LIB conference bridge as such
2116  * so that channel0/left channel of the sound device corresponds to
2117  * slot 0 in the bridge, and channel1/right channel of the sound
2118  * device corresponds to slot 1 in the bridge. Then user can independently
2119  * feed different media to/from the speakers/microphones channels, by
2120  * connecting them to slot 0 or 1 respectively.
2121  *
2122  * Here's how the connection looks like:
2123  *
2124    +-----------+ stereo +-----------------+ 2x mono +-----------+
2125    | AUDIO DEV |<------>| SPLITCOMB   left|<------->|#0  BRIDGE |
2126    +-----------+        |            right|<------->|#1         |
2127                         +-----------------+         +-----------+
2128  */
stereo_demo()2129 static void stereo_demo()
2130 {
2131     pjmedia_port *conf;
2132     pj_status_t status;
2133 
2134     /* Disable existing sound device */
2135     conf = pjsua_set_no_snd_dev();
2136 
2137     /* Create stereo-mono splitter/combiner */
2138     status = pjmedia_splitcomb_create(app_config.pool,
2139 				PJMEDIA_PIA_SRATE(&conf->info) /* clock rate */,
2140 				2	    /* stereo */,
2141 				2 * PJMEDIA_PIA_SPF(&conf->info),
2142 				PJMEDIA_PIA_BITS(&conf->info),
2143 				0	    /* options */,
2144 				&app_config.sc);
2145     pj_assert(status == PJ_SUCCESS);
2146 
2147     /* Connect channel0 (left channel?) to conference port slot0 */
2148     status = pjmedia_splitcomb_set_channel(app_config.sc, 0 /* ch0 */,
2149 					   0 /*options*/,
2150 					   conf);
2151     pj_assert(status == PJ_SUCCESS);
2152 
2153     /* Create reverse channel for channel1 (right channel?)... */
2154     status = pjmedia_splitcomb_create_rev_channel(app_config.pool,
2155 						  app_config.sc,
2156 						  1  /* ch1 */,
2157 						  0  /* options */,
2158 						  &app_config.sc_ch1);
2159     pj_assert(status == PJ_SUCCESS);
2160 
2161     /* .. and register it to conference bridge (it would be slot1
2162      * if there's no other devices connected to the bridge)
2163      */
2164     status = pjsua_conf_add_port(app_config.pool, app_config.sc_ch1,
2165 				 &app_config.sc_ch1_slot);
2166     pj_assert(status == PJ_SUCCESS);
2167 
2168     /* Create sound device */
2169     status = pjmedia_snd_port_create(app_config.pool, -1, -1,
2170 				     PJMEDIA_PIA_SRATE(&conf->info),
2171 				     2	    /* stereo */,
2172 				     2 * PJMEDIA_PIA_SPF(&conf->info),
2173 				     PJMEDIA_PIA_BITS(&conf->info),
2174 				     0, &app_config.snd);
2175 
2176     pj_assert(status == PJ_SUCCESS);
2177 
2178 
2179     /* Connect the splitter to the sound device */
2180     status = pjmedia_snd_port_connect(app_config.snd, app_config.sc);
2181     pj_assert(status == PJ_SUCCESS);
2182 }
2183 #endif
2184