]> sjero.net Git - linphone/blob - coreapi/linphonecore.c
implement call recording.
[linphone] / coreapi / linphonecore.c
1 /*
2 linphone
3 Copyright (C) 2000  Simon MORLAT (simon.morlat@linphone.org)
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20 #define _GNU_SOURCE
21
22 #include "linphonecore.h"
23 #include "sipsetup.h"
24 #include "lpconfig.h"
25 #include "private.h"
26
27 #include <math.h>
28 #include <ortp/telephonyevents.h>
29 #include <ortp/zrtp.h>
30 #include "mediastreamer2/mediastream.h"
31 #include "mediastreamer2/mseventqueue.h"
32 #include "mediastreamer2/msvolume.h"
33 #include "mediastreamer2/msequalizer.h"
34 #include "mediastreamer2/dtmfgen.h"
35
36 #ifdef INET6
37 #ifndef WIN32
38 #include <netdb.h>
39 #endif
40 #endif
41
42 #ifdef HAVE_CONFIG_H
43 #include "config.h"
44 #include "liblinphone_gitversion.h"
45 #else
46 #ifndef LIBLINPHONE_GIT_VERSION
47 #define LIBLINPHONE_GIT_VERSION "unknown"
48 #endif
49 #endif
50
51
52 /*#define UNSTANDART_GSM_11K 1*/
53
54 #define ROOT_CA_FILE PACKAGE_DATA_DIR "/linphone/rootca.pem"
55
56 static const char *liblinphone_version=
57 #ifdef LIBLINPHONE_GIT_VERSION
58         LIBLINPHONE_GIT_VERSION
59 #else
60         LIBLINPHONE_VERSION
61 #endif
62 ;
63 static void set_network_reachable(LinphoneCore* lc,bool_t isReachable, time_t curtime);
64 static void linphone_core_run_hooks(LinphoneCore *lc);
65 static void linphone_core_free_hooks(LinphoneCore *lc);
66
67 #include "enum.h"
68
69 const char *linphone_core_get_nat_address_resolved(LinphoneCore *lc);
70 static void toggle_video_preview(LinphoneCore *lc, bool_t val);
71
72 /* relative path where is stored local ring*/
73 #define LOCAL_RING "rings/oldphone.wav"
74 /* same for remote ring (ringback)*/
75 #define REMOTE_RING "ringback.wav"
76 #define HOLD_MUSIC "rings/toy-mono.wav"
77
78
79 extern SalCallbacks linphone_sal_callbacks;
80
81 void lc_callback_obj_init(LCCallbackObj *obj,LinphoneCoreCbFunc func,void* ud)
82 {
83   obj->_func=func;
84   obj->_user_data=ud;
85 }
86
87 int lc_callback_obj_invoke(LCCallbackObj *obj, LinphoneCore *lc){
88         if (obj->_func!=NULL) obj->_func(lc,obj->_user_data);
89         return 0;
90 }
91
92
93 /*prevent a gcc bug with %c*/
94 static size_t my_strftime(char *s, size_t max, const char  *fmt,  const struct tm *tm){
95 #if !defined(_WIN32_WCE)
96         return strftime(s, max, fmt, tm);
97 #else
98         return 0;
99         /*FIXME*/
100 #endif /*_WIN32_WCE*/
101 }
102
103 static void set_call_log_date(LinphoneCallLog *cl, time_t start_time){
104         struct tm loctime;
105 #ifdef WIN32
106 #if !defined(_WIN32_WCE)
107         loctime=*localtime(&start_time);
108         /*FIXME*/
109 #endif /*_WIN32_WCE*/
110 #else
111         localtime_r(&start_time,&loctime);
112 #endif
113         my_strftime(cl->start_date,sizeof(cl->start_date),"%c",&loctime);
114 }
115
116 LinphoneCallLog * linphone_call_log_new(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
117         LinphoneCallLog *cl=ms_new0(LinphoneCallLog,1);
118         cl->dir=call->dir;
119         cl->start_date_time=call->start_time;
120         set_call_log_date(cl,cl->start_date_time);
121         cl->from=from;
122         cl->to=to;
123     cl->status=LinphoneCallAborted; /*default status*/
124         return cl;
125 }
126
127 void call_logs_write_to_config_file(LinphoneCore *lc){
128         MSList *elem;
129         char logsection[32];
130         int i;
131         char *tmp;
132         LpConfig *cfg=lc->config;
133
134         if (linphone_core_get_global_state (lc)==LinphoneGlobalStartup) return;
135
136         for(i=0,elem=lc->call_logs;elem!=NULL;elem=elem->next,++i){
137                 LinphoneCallLog *cl=(LinphoneCallLog*)elem->data;
138                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
139                 lp_config_clean_section(cfg,logsection);
140                 lp_config_set_int(cfg,logsection,"dir",cl->dir);
141                 lp_config_set_int(cfg,logsection,"status",cl->status);
142                 tmp=linphone_address_as_string(cl->from);
143                 lp_config_set_string(cfg,logsection,"from",tmp);
144                 ms_free(tmp);
145                 tmp=linphone_address_as_string(cl->to);
146                 lp_config_set_string(cfg,logsection,"to",tmp);
147                 ms_free(tmp);
148                 if (cl->start_date_time)
149                         lp_config_set_int64(cfg,logsection,"start_date_time",(int64_t)cl->start_date_time);
150                 else lp_config_set_string(cfg,logsection,"start_date",cl->start_date);
151                 lp_config_set_int(cfg,logsection,"duration",cl->duration);
152                 if (cl->refkey) lp_config_set_string(cfg,logsection,"refkey",cl->refkey);
153                 lp_config_set_float(cfg,logsection,"quality",cl->quality);
154                 lp_config_set_int(cfg,logsection,"video_enabled", cl->video_enabled);
155                 lp_config_set_string(cfg,logsection,"call_id",cl->call_id);
156         }
157         for(;i<lc->max_call_logs;++i){
158                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
159                 lp_config_clean_section(cfg,logsection);
160         }
161 }
162
163 static time_t string_to_time(const char *date){
164 #ifndef WIN32
165         struct tm tmtime={0};
166         strptime(date,"%c",&tmtime);
167         return mktime(&tmtime);
168 #else
169         return 0;
170 #endif
171 }
172
173 static void call_logs_read_from_config_file(LinphoneCore *lc){
174         char logsection[32];
175         int i;
176         const char *tmp;
177         uint64_t sec;
178         LpConfig *cfg=lc->config;
179         for(i=0;;++i){
180                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
181                 if (lp_config_has_section(cfg,logsection)){
182                         LinphoneCallLog *cl=ms_new0(LinphoneCallLog,1);
183                         cl->dir=lp_config_get_int(cfg,logsection,"dir",0);
184                         cl->status=lp_config_get_int(cfg,logsection,"status",0);
185                         tmp=lp_config_get_string(cfg,logsection,"from",NULL);
186                         if (tmp) cl->from=linphone_address_new(tmp);
187                         tmp=lp_config_get_string(cfg,logsection,"to",NULL);
188                         if (tmp) cl->to=linphone_address_new(tmp);
189                         sec=lp_config_get_int64(cfg,logsection,"start_date_time",0);
190                         if (sec) {
191                                 /*new call log format with date expressed in seconds */
192                                 cl->start_date_time=(time_t)sec;
193                                 set_call_log_date(cl,cl->start_date_time);
194                         }else{
195                                 tmp=lp_config_get_string(cfg,logsection,"start_date",NULL);
196                                 if (tmp) {
197                                         strncpy(cl->start_date,tmp,sizeof(cl->start_date));
198                                         cl->start_date_time=string_to_time(cl->start_date);
199                                 }
200                         }
201                         cl->duration=lp_config_get_int(cfg,logsection,"duration",0);
202                         tmp=lp_config_get_string(cfg,logsection,"refkey",NULL);
203                         if (tmp) cl->refkey=ms_strdup(tmp);
204                         cl->quality=lp_config_get_float(cfg,logsection,"quality",-1);
205                         cl->video_enabled=lp_config_get_int(cfg,logsection,"video_enabled",0);
206                         cl->call_id=lp_config_get_string(cfg,logsection,"call_id",NULL);
207                         if(cl->call_id) cl->call_id=ms_strdup(cl->call_id);
208                         lc->call_logs=ms_list_append(lc->call_logs,cl);
209                 }else break;
210         }
211 }
212
213
214
215 /**
216  * @addtogroup call_logs
217  * @{
218 **/
219
220 /**
221  * Returns a human readable string describing the call.
222  *
223  * @note: the returned char* must be freed by the application (use ms_free()).
224 **/
225 char * linphone_call_log_to_str(LinphoneCallLog *cl){
226         char *status;
227         char *tmp;
228         char *from=linphone_address_as_string (cl->from);
229         char *to=linphone_address_as_string (cl->to);
230         switch(cl->status){
231                 case LinphoneCallAborted:
232                         status=_("aborted");
233                         break;
234                 case LinphoneCallSuccess:
235                         status=_("completed");
236                         break;
237                 case LinphoneCallMissed:
238                         status=_("missed");
239                         break;
240                 default:
241                         status="unknown";
242         }
243         tmp=ortp_strdup_printf(_("%s at %s\nFrom: %s\nTo: %s\nStatus: %s\nDuration: %i mn %i sec\n"),
244                         (cl->dir==LinphoneCallIncoming) ? _("Incoming call") : _("Outgoing call"),
245                         cl->start_date,
246                         from,
247                         to,
248                         status,
249                         cl->duration/60,
250                         cl->duration%60);
251         ms_free(from);
252         ms_free(to);
253         return tmp;
254 }
255
256 /**
257  * Returns RTP statistics computed locally regarding the call.
258  *
259 **/
260 const rtp_stats_t *linphone_call_log_get_local_stats(const LinphoneCallLog *cl){
261         return &cl->local_stats;
262 }
263
264 /**
265  * Returns RTP statistics computed by remote end and sent back via RTCP.
266  *
267  * @note Not implemented yet.
268 **/
269 const rtp_stats_t *linphone_call_log_get_remote_stats(const LinphoneCallLog *cl){
270         return &cl->remote_stats;
271 }
272
273 void linphone_call_log_set_user_pointer(LinphoneCallLog *cl, void *up){
274         cl->user_pointer=up;
275 }
276
277 void *linphone_call_log_get_user_pointer(const LinphoneCallLog *cl){
278         return cl->user_pointer;
279 }
280
281
282
283 /**
284  * Associate a persistent reference key to the call log.
285  *
286  * The reference key can be for example an id to an external database.
287  * It is stored in the config file, thus can survive to process exits/restarts.
288  *
289 **/
290 void linphone_call_log_set_ref_key(LinphoneCallLog *cl, const char *refkey){
291         if (cl->refkey!=NULL){
292                 ms_free(cl->refkey);
293                 cl->refkey=NULL;
294         }
295         if (refkey) cl->refkey=ms_strdup(refkey);
296 }
297
298 /**
299  * Get the persistent reference key associated to the call log.
300  *
301  * The reference key can be for example an id to an external database.
302  * It is stored in the config file, thus can survive to process exits/restarts.
303  *
304 **/
305 const char *linphone_call_log_get_ref_key(const LinphoneCallLog *cl){
306         return cl->refkey;
307 }
308
309 /** @} */
310
311 void linphone_call_log_destroy(LinphoneCallLog *cl){
312         if (cl->from!=NULL) linphone_address_destroy(cl->from);
313         if (cl->to!=NULL) linphone_address_destroy(cl->to);
314         if (cl->refkey!=NULL) ms_free(cl->refkey);
315         if (cl->call_id) ms_free((void*)cl->call_id);
316         ms_free(cl);
317 }
318
319 /**
320  * Returns TRUE if the LinphoneCall asked to autoanswer
321  *
322 **/
323 bool_t linphone_call_asked_to_autoanswer(LinphoneCall *call){
324         //return TRUE if the unique(for the moment) incoming call asked to be autoanswered
325         if(call)
326                 return sal_call_autoanswer_asked(call->op);
327         else
328                 return FALSE;
329 }
330
331 int linphone_core_get_current_call_duration(const LinphoneCore *lc){
332         LinphoneCall *call=linphone_core_get_current_call((LinphoneCore *)lc);
333         if (call)  return linphone_call_get_duration(call);
334         return -1;
335 }
336
337 const LinphoneAddress *linphone_core_get_current_call_remote_address(struct _LinphoneCore *lc){
338         LinphoneCall *call=linphone_core_get_current_call(lc);
339         if (call==NULL) return NULL;
340         return linphone_call_get_remote_address(call);
341 }
342
343 /**
344  * Enable logs in supplied FILE*.
345  *
346  * @ingroup misc
347  *
348  * @param file a C FILE* where to fprintf logs. If null stdout is used.
349  *
350 **/
351 void linphone_core_enable_logs(FILE *file){
352         if (file==NULL) file=stdout;
353         ortp_set_log_file(file);
354         ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
355 }
356
357 /**
358  * Enable logs through the user's supplied log callback.
359  *
360  * @ingroup misc
361  *
362  * @param logfunc The address of a OrtpLogFunc callback whose protoype is
363  *                typedef void (*OrtpLogFunc)(OrtpLogLevel lev, const char *fmt, va_list args);
364  *
365 **/
366 void linphone_core_enable_logs_with_cb(OrtpLogFunc logfunc){
367         ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
368         ortp_set_log_handler(logfunc);
369 }
370
371 /**
372  * Entirely disable logging.
373  *
374  * @ingroup misc
375 **/
376 void linphone_core_disable_logs(){
377         ortp_set_log_level_mask(ORTP_ERROR|ORTP_FATAL);
378 }
379
380
381 static void net_config_read (LinphoneCore *lc)
382 {
383         int tmp;
384         const char *tmpstr;
385         LpConfig *config=lc->config;
386
387         lc->net_conf.nat_address_ip = NULL;
388         tmp=lp_config_get_int(config,"net","download_bw",0);
389         linphone_core_set_download_bandwidth(lc,tmp);
390         tmp=lp_config_get_int(config,"net","upload_bw",0);
391         linphone_core_set_upload_bandwidth(lc,tmp);
392         linphone_core_set_stun_server(lc,lp_config_get_string(config,"net","stun_server",NULL));
393         tmpstr=lp_config_get_string(lc->config,"net","nat_address",NULL);
394         if (tmpstr!=NULL && (strlen(tmpstr)<1)) tmpstr=NULL;
395         linphone_core_set_nat_address(lc,tmpstr);
396         tmp=lp_config_get_int(lc->config,"net","firewall_policy",0);
397         linphone_core_set_firewall_policy(lc,tmp);
398         tmp=lp_config_get_int(lc->config,"net","nat_sdp_only",0);
399         lc->net_conf.nat_sdp_only=tmp;
400         tmp=lp_config_get_int(lc->config,"net","mtu",0);
401         linphone_core_set_mtu(lc,tmp);
402         tmp=lp_config_get_int(lc->config,"net","download_ptime",0);
403         linphone_core_set_download_ptime(lc,tmp);
404
405 }
406
407 static void build_sound_devices_table(LinphoneCore *lc){
408         const char **devices;
409         const char **old;
410         int ndev;
411         int i;
412         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
413         ndev=ms_list_size(elem);
414         devices=ms_malloc((ndev+1)*sizeof(const char *));
415         for (i=0;elem!=NULL;elem=elem->next,i++){
416                 devices[i]=ms_snd_card_get_string_id((MSSndCard *)elem->data);
417         }
418         devices[ndev]=NULL;
419         old=lc->sound_conf.cards;
420         lc->sound_conf.cards=devices;
421         if (old!=NULL) ms_free(old);
422 }
423
424 static void sound_config_read(LinphoneCore *lc)
425 {
426         int tmp;
427         const char *tmpbuf;
428         const char *devid;
429 #ifdef __linux
430         /*alsadev let the user use custom alsa device within linphone*/
431         devid=lp_config_get_string(lc->config,"sound","alsadev",NULL);
432         if (devid){
433                 MSSndCard *card=ms_alsa_card_new_custom(devid,devid);
434                 ms_snd_card_manager_add_card(ms_snd_card_manager_get(),card);
435         }
436         tmp=lp_config_get_int(lc->config,"sound","alsa_forced_rate",-1);
437         if (tmp>0) ms_alsa_card_set_forced_sample_rate(tmp);
438 #endif
439         /* retrieve all sound devices */
440         build_sound_devices_table(lc);
441
442         devid=lp_config_get_string(lc->config,"sound","playback_dev_id",NULL);
443         linphone_core_set_playback_device(lc,devid);
444
445         devid=lp_config_get_string(lc->config,"sound","ringer_dev_id",NULL);
446         linphone_core_set_ringer_device(lc,devid);
447
448         devid=lp_config_get_string(lc->config,"sound","capture_dev_id",NULL);
449         linphone_core_set_capture_device(lc,devid);
450
451 /*
452         tmp=lp_config_get_int(lc->config,"sound","play_lev",80);
453         linphone_core_set_play_level(lc,tmp);
454         tmp=lp_config_get_int(lc->config,"sound","ring_lev",80);
455         linphone_core_set_ring_level(lc,tmp);
456         tmp=lp_config_get_int(lc->config,"sound","rec_lev",80);
457         linphone_core_set_rec_level(lc,tmp);
458         tmpbuf=lp_config_get_string(lc->config,"sound","source","m");
459         linphone_core_set_sound_source(lc,tmpbuf[0]);
460 */
461
462         tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
463         tmpbuf=lp_config_get_string(lc->config,"sound","local_ring",tmpbuf);
464         if (ortp_file_exist(tmpbuf)==-1) {
465                 ms_warning("%s does not exist",tmpbuf);
466                 tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
467         }
468         if (strstr(tmpbuf,".wav")==NULL){
469                 /* it currently uses old sound files, so replace them */
470                 tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
471         }
472         linphone_core_set_ring(lc,tmpbuf);
473
474         tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
475         tmpbuf=lp_config_get_string(lc->config,"sound","remote_ring",tmpbuf);
476         if (ortp_file_exist(tmpbuf)==-1){
477                 tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
478         }
479         if (strstr(tmpbuf,".wav")==NULL){
480                 /* it currently uses old sound files, so replace them */
481                 tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
482         }
483         linphone_core_set_ringback(lc,tmpbuf);
484
485         linphone_core_set_play_file(lc,lp_config_get_string(lc->config,"sound","hold_music",PACKAGE_SOUND_DIR "/" HOLD_MUSIC));
486         check_sound_device(lc);
487         lc->sound_conf.latency=0;
488 #ifndef __ios 
489         tmp=TRUE;
490 #else
491         tmp=FALSE; /* on iOS we have builtin echo cancellation.*/
492 #endif
493         tmp=lp_config_get_int(lc->config,"sound","echocancellation",tmp);
494         linphone_core_enable_echo_cancellation(lc,tmp);
495         linphone_core_enable_echo_limiter(lc,
496                 lp_config_get_int(lc->config,"sound","echolimiter",0));
497         linphone_core_enable_agc(lc,
498                 lp_config_get_int(lc->config,"sound","agc",0));
499
500         linphone_core_set_playback_gain_db (lc,lp_config_get_float(lc->config,"sound","playback_gain_db",0));
501         linphone_core_set_mic_gain_db (lc,lp_config_get_float(lc->config,"sound","mic_gain_db",0));
502
503         linphone_core_set_remote_ringback_tone (lc,lp_config_get_string(lc->config,"sound","ringback_tone",NULL));
504
505         /*just parse requested stream feature once at start to print out eventual errors*/
506         linphone_core_get_audio_features(lc);
507 }
508
509 static void sip_config_read(LinphoneCore *lc)
510 {
511         char *contact;
512         const char *tmpstr;
513         LCSipTransports tr;
514         int i,tmp;
515         int ipv6;
516         int random_port;
517
518         tmp=lp_config_get_int(lc->config,"sip","use_info",0);
519         linphone_core_set_use_info_for_dtmf(lc,tmp);
520
521         if (lp_config_get_int(lc->config,"sip","use_session_timers",0)==1){
522                 sal_use_session_timers(lc->sal,200);
523         }
524
525         sal_use_rport(lc->sal,lp_config_get_int(lc->config,"sip","use_rport",1));
526         sal_use_101(lc->sal,lp_config_get_int(lc->config,"sip","use_101",1));
527         sal_reuse_authorization(lc->sal, lp_config_get_int(lc->config,"sip","reuse_authorization",0));
528         sal_expire_old_registration_contacts(lc->sal,lp_config_get_int(lc->config,"sip","expire_old_registration_contacts",0));
529
530         tmp=lp_config_get_int(lc->config,"sip","use_rfc2833",1);
531         linphone_core_set_use_rfc2833_for_dtmf(lc,tmp);
532
533         ipv6=lp_config_get_int(lc->config,"sip","use_ipv6",-1);
534         if (ipv6==-1){
535                 ipv6=0;
536         }
537         linphone_core_enable_ipv6(lc,ipv6);
538         memset(&tr,0,sizeof(tr));
539         
540         tr.udp_port=lp_config_get_int(lc->config,"sip","sip_port",0);
541         tr.tcp_port=lp_config_get_int(lc->config,"sip","sip_tcp_port",0);
542         tr.tls_port=lp_config_get_int(lc->config,"sip","sip_tls_port",0);
543         
544         if (lp_config_get_int(lc->config,"sip","sip_random_port",0)==1)
545                 random_port=(0xDFFF&random())+1024;
546         else random_port=0;
547         
548         if (tr.udp_port==0 && tr.tcp_port==0 && tr.tls_port==0){
549                 tr.udp_port=5060;
550         }       
551         
552         if (tr.udp_port>0 && random_port){
553                 tr.udp_port=random_port;
554                 tr.tls_port=tr.tcp_port=0; /*make sure only one transport is active at a time*/
555         }else if (tr.tcp_port>0 && random_port){
556                 tr.tcp_port=random_port;
557                 tr.tls_port=tr.udp_port=0; /*make sure only one transport is active at a time*/
558         }else if (tr.tls_port>0 && random_port){
559                 tr.tls_port=random_port;
560                 tr.udp_port=tr.tcp_port=0; /*make sure only one transport is active at a time*/
561         } 
562
563 #ifdef __linux
564         sal_set_root_ca(lc->sal, lp_config_get_string(lc->config,"sip","root_ca", "/etc/ssl/certs"));
565 #else
566         sal_set_root_ca(lc->sal, lp_config_get_string(lc->config,"sip","root_ca", ROOT_CA_FILE));
567 #endif
568         linphone_core_verify_server_certificates(lc,lp_config_get_int(lc->config,"sip","verify_server_certs",TRUE));
569         linphone_core_verify_server_cn(lc,lp_config_get_int(lc->config,"sip","verify_server_cn",TRUE));
570         /*setting the dscp must be done before starting the transports, otherwise it is not taken into effect*/
571         sal_set_dscp(lc->sal,linphone_core_get_sip_dscp(lc));
572         /*start listening on ports*/
573         linphone_core_set_sip_transports(lc,&tr);
574
575         tmpstr=lp_config_get_string(lc->config,"sip","contact",NULL);
576         if (tmpstr==NULL || linphone_core_set_primary_contact(lc,tmpstr)==-1) {
577                 const char *hostname=NULL;
578                 const char *username=NULL;
579 #ifdef HAVE_GETENV
580                 hostname=getenv("HOST");
581                 username=getenv("USER");
582                 if (hostname==NULL) hostname=getenv("HOSTNAME");
583 #endif /*HAVE_GETENV*/
584                 if (hostname==NULL)
585                         hostname="unknown-host";
586                 if (username==NULL){
587                         username="toto";
588                 }
589                 contact=ortp_strdup_printf("sip:%s@%s",username,hostname);
590                 linphone_core_set_primary_contact(lc,contact);
591                 ms_free(contact);
592         }
593
594         tmp=lp_config_get_int(lc->config,"sip","guess_hostname",1);
595         linphone_core_set_guess_hostname(lc,tmp);
596
597
598         tmp=lp_config_get_int(lc->config,"sip","inc_timeout",30);
599         linphone_core_set_inc_timeout(lc,tmp);
600
601         tmp=lp_config_get_int(lc->config,"sip","in_call_timeout",0);
602         linphone_core_set_in_call_timeout(lc,tmp);
603
604         /* get proxies config */
605         for(i=0;; i++){
606                 LinphoneProxyConfig *cfg=linphone_proxy_config_new_from_config_file(lc->config,i);
607                 if (cfg!=NULL){
608                         linphone_core_add_proxy_config(lc,cfg);
609                 }else{
610                         break;
611                 }
612         }
613         /* get the default proxy */
614         tmp=lp_config_get_int(lc->config,"sip","default_proxy",-1);
615         linphone_core_set_default_proxy_index(lc,tmp);
616
617         /* read authentication information */
618         for(i=0;; i++){
619                 LinphoneAuthInfo *ai=linphone_auth_info_new_from_config_file(lc->config,i);
620                 if (ai!=NULL){
621                         linphone_core_add_auth_info(lc,ai);
622                         linphone_auth_info_destroy(ai);
623                 }else{
624                         break;
625                 }
626         }
627         /*this is to filter out unsupported encryption schemes*/
628         linphone_core_set_media_encryption(lc,linphone_core_get_media_encryption(lc));
629
630         /*for tuning or test*/
631         lc->sip_conf.sdp_200_ack=lp_config_get_int(lc->config,"sip","sdp_200_ack",0);
632         lc->sip_conf.register_only_when_network_is_up=
633                 lp_config_get_int(lc->config,"sip","register_only_when_network_is_up",1);
634         lc->sip_conf.ping_with_options=lp_config_get_int(lc->config,"sip","ping_with_options",1);
635         lc->sip_conf.auto_net_state_mon=lp_config_get_int(lc->config,"sip","auto_net_state_mon",1);
636         lc->sip_conf.keepalive_period=lp_config_get_int(lc->config,"sip","keepalive_period",10000);
637         lc->sip_conf.tcp_tls_keepalive=lp_config_get_int(lc->config,"sip","tcp_tls_keepalive",0);
638         linphone_core_enable_keep_alive(lc, (lc->sip_conf.keepalive_period > 0));
639         sal_use_one_matching_codec_policy(lc->sal,lp_config_get_int(lc->config,"sip","only_one_codec",0));
640         sal_use_double_registrations(lc->sal,lp_config_get_int(lc->config,"sip","use_double_registrations",1));
641         sal_use_dates(lc->sal,lp_config_get_int(lc->config,"sip","put_date",0));
642 }
643
644 static void rtp_config_read(LinphoneCore *lc)
645 {
646         int min_port, max_port;
647         int jitt_comp;
648         int nortp_timeout;
649         bool_t rtp_no_xmit_on_audio_mute;
650         bool_t adaptive_jitt_comp_enabled;
651
652         if (lp_config_get_range(lc->config, "rtp", "audio_rtp_port", &min_port, &max_port, 7078, 7078) == TRUE) {
653                 if (min_port <= 0) min_port = 1;
654                 if (max_port > 65535) max_port = 65535;
655                 linphone_core_set_audio_port_range(lc, min_port, max_port);
656         } else {
657                 min_port = lp_config_get_int(lc->config, "rtp", "audio_rtp_port", 7078);
658                 linphone_core_set_audio_port(lc, min_port);
659         }
660
661         if (lp_config_get_range(lc->config, "rtp", "video_rtp_port", &min_port, &max_port, 9078, 9078) == TRUE) {
662                 if (min_port <= 0) min_port = 1;
663                 if (max_port > 65535) max_port = 65535;
664                 linphone_core_set_video_port_range(lc, min_port, max_port);
665         } else {
666                 min_port = lp_config_get_int(lc->config, "rtp", "video_rtp_port", 9078);
667                 linphone_core_set_video_port(lc, min_port);
668         }
669
670         jitt_comp=lp_config_get_int(lc->config,"rtp","audio_jitt_comp",60);
671         linphone_core_set_audio_jittcomp(lc,jitt_comp);
672         jitt_comp=lp_config_get_int(lc->config,"rtp","video_jitt_comp",60);
673         if (jitt_comp==0) jitt_comp=60;
674         linphone_core_set_video_jittcomp(lc,jitt_comp);
675         nortp_timeout=lp_config_get_int(lc->config,"rtp","nortp_timeout",30);
676         linphone_core_set_nortp_timeout(lc,nortp_timeout);
677         rtp_no_xmit_on_audio_mute=lp_config_get_int(lc->config,"rtp","rtp_no_xmit_on_audio_mute",FALSE);
678         linphone_core_set_rtp_no_xmit_on_audio_mute(lc,rtp_no_xmit_on_audio_mute);
679         adaptive_jitt_comp_enabled = lp_config_get_int(lc->config, "rtp", "audio_adaptive_jitt_comp_enabled", TRUE);
680         linphone_core_enable_audio_adaptive_jittcomp(lc, adaptive_jitt_comp_enabled);
681         adaptive_jitt_comp_enabled = lp_config_get_int(lc->config, "rtp", "video_adaptive_jitt_comp_enabled", TRUE);
682         linphone_core_enable_video_adaptive_jittcomp(lc, adaptive_jitt_comp_enabled);
683 }
684
685 static PayloadType * find_payload(RtpProfile *prof, const char *mime_type, int clock_rate, int channels, const char *recv_fmtp){
686         PayloadType *candidate=NULL;
687         int i;
688         PayloadType *it;
689         for(i=0;i<RTP_PROFILE_MAX_PAYLOADS;++i){
690                 it=rtp_profile_get_payload(prof,i);
691                 if (it!=NULL && strcasecmp(mime_type,it->mime_type)==0
692                         && (clock_rate==it->clock_rate || clock_rate<=0)
693                         && (channels==it->channels || channels<=0) ){
694                         if ( (recv_fmtp && it->recv_fmtp && strstr(recv_fmtp,it->recv_fmtp)!=NULL) ||
695                                 (recv_fmtp==NULL && it->recv_fmtp==NULL) ){
696                                 /*exact match*/
697                                 if (recv_fmtp) payload_type_set_recv_fmtp(it,recv_fmtp);
698                                 return it;
699                         }else {
700                                 if (candidate){
701                                         if (it->recv_fmtp==NULL) candidate=it;
702                                 }else candidate=it;
703                         }
704                 }
705         }
706         if (candidate && recv_fmtp){
707                 payload_type_set_recv_fmtp(candidate,recv_fmtp);
708         }
709         return candidate;
710 }
711
712 static bool_t get_codec(LinphoneCore *lc, const char* type, int index, PayloadType **ret){
713         char codeckey[50];
714         const char *mime,*fmtp;
715         int rate,channels,enabled;
716         PayloadType *pt;
717         LpConfig *config=lc->config;
718
719         *ret=NULL;
720         snprintf(codeckey,50,"%s_%i",type,index);
721         mime=lp_config_get_string(config,codeckey,"mime",NULL);
722         if (mime==NULL || strlen(mime)==0 ) return FALSE;
723
724         rate=lp_config_get_int(config,codeckey,"rate",8000);
725         fmtp=lp_config_get_string(config,codeckey,"recv_fmtp",NULL);
726         channels=lp_config_get_int(config,codeckey,"channels",0);
727         enabled=lp_config_get_int(config,codeckey,"enabled",1);
728         pt=find_payload(lc->default_profile,mime,rate,channels,fmtp);
729         if (pt && enabled ) pt->flags|=PAYLOAD_TYPE_ENABLED;
730         //ms_message("Found codec %s/%i",pt->mime_type,pt->clock_rate);
731         if (pt==NULL) ms_warning("Ignoring codec config %s/%i with fmtp=%s because unsupported",
732                         mime,rate,fmtp ? fmtp : "");
733         *ret=pt;
734         return TRUE;
735 }
736
737 #define RANK_END 10000
738
739 typedef struct codec_desc{
740         const char *name;
741         int rate;
742 }codec_desc_t;
743
744 static codec_desc_t codec_pref_order[]={
745         {"SILK", 16000},
746         {"speex", 16000},
747         {"speex", 8000},
748         {"pcmu",8000},
749         {"pcma",8000},
750         {"VP8",90000},
751         {"H264",90000},
752         {"MP4V-ES",90000},
753         {NULL,0}
754 };
755
756 static int find_codec_rank(const char *mime, int clock_rate){
757         int i;
758         for(i=0;codec_pref_order[i].name!=NULL;++i){
759                 if (strcasecmp(codec_pref_order[i].name,mime)==0 && clock_rate==codec_pref_order[i].rate)
760                         return i;
761         }
762         return RANK_END;
763 }
764
765 static int codec_compare(const PayloadType *a, const PayloadType *b){
766         int ra,rb;
767         ra=find_codec_rank(a->mime_type,a->clock_rate);
768         rb=find_codec_rank(b->mime_type,b->clock_rate);
769         if (ra>rb) return 1;
770         if (ra<rb) return -1;
771         return 0;
772 }
773
774 static MSList *add_missing_codecs(LinphoneCore *lc, SalStreamType mtype, MSList *l){
775         int i;
776         for(i=0;i<RTP_PROFILE_MAX_PAYLOADS;++i){
777                 PayloadType *pt=rtp_profile_get_payload(lc->default_profile,i);
778                 if (pt){
779                         if (mtype==SalVideo && pt->type!=PAYLOAD_VIDEO)
780                                 pt=NULL;
781                         else if (mtype==SalAudio && (pt->type!=PAYLOAD_AUDIO_PACKETIZED
782                             && pt->type!=PAYLOAD_AUDIO_CONTINUOUS)){
783                                 pt=NULL;
784                         }
785                         if (pt && ms_filter_codec_supported(pt->mime_type)){
786                                 if (ms_list_find(l,pt)==NULL){
787                                         /*unranked codecs are disabled by default*/
788                                         if (find_codec_rank(pt->mime_type, pt->clock_rate)!=RANK_END){
789                                                 payload_type_set_flag(pt,PAYLOAD_TYPE_ENABLED);
790                                         }
791                                         ms_message("Adding new codec %s/%i with fmtp %s",
792                                             pt->mime_type,pt->clock_rate,pt->recv_fmtp ? pt->recv_fmtp : "");
793                                         l=ms_list_insert_sorted(l,pt,(int (*)(const void *, const void *))codec_compare);
794                                 }
795                         }
796                 }
797         }
798         return l;
799 }
800
801 static MSList *codec_append_if_new(MSList *l, PayloadType *pt){
802         MSList *elem;
803         for (elem=l;elem!=NULL;elem=elem->next){
804                 PayloadType *ept=(PayloadType*)elem->data;
805                 if (pt==ept)
806                         return l;
807         }
808         l=ms_list_append(l,pt);
809         return l;
810 }
811
812 static void codecs_config_read(LinphoneCore *lc)
813 {
814         int i;
815         PayloadType *pt;
816         MSList *audio_codecs=NULL;
817         MSList *video_codecs=NULL;
818         for (i=0;get_codec(lc,"audio_codec",i,&pt);i++){
819                 if (pt){
820                         if (!ms_filter_codec_supported(pt->mime_type)){
821                                 ms_warning("Codec %s is not supported by mediastreamer2, removed.",pt->mime_type);
822                         }else audio_codecs=codec_append_if_new(audio_codecs,pt);
823                 }
824         }
825         audio_codecs=add_missing_codecs(lc,SalAudio,audio_codecs);
826         for (i=0;get_codec(lc,"video_codec",i,&pt);i++){
827                 if (pt){
828                         if (!ms_filter_codec_supported(pt->mime_type)){
829                                 ms_warning("Codec %s is not supported by mediastreamer2, removed.",pt->mime_type);
830                         }else video_codecs=codec_append_if_new(video_codecs,(void *)pt);
831                 }
832         }
833         video_codecs=add_missing_codecs(lc,SalVideo,video_codecs);
834         linphone_core_set_audio_codecs(lc,audio_codecs);
835         linphone_core_set_video_codecs(lc,video_codecs);
836         linphone_core_update_allocated_audio_bandwidth(lc);
837 }
838
839 static void build_video_devices_table(LinphoneCore *lc){
840         const MSList *elem;
841         int i;
842         int ndev;
843         const char **devices;
844         if (lc->video_conf.cams)
845                 ms_free(lc->video_conf.cams);
846         /* retrieve all video devices */
847         elem=ms_web_cam_manager_get_list(ms_web_cam_manager_get());
848         ndev=ms_list_size(elem);
849         devices=ms_malloc((ndev+1)*sizeof(const char *));
850         for (i=0;elem!=NULL;elem=elem->next,i++){
851                 devices[i]=ms_web_cam_get_string_id((MSWebCam *)elem->data);
852         }
853         devices[ndev]=NULL;
854         lc->video_conf.cams=devices;
855 }
856
857 static void video_config_read(LinphoneCore *lc){
858 #ifdef VIDEO_ENABLED
859         int capture, display, self_view;
860 #endif
861         const char *str;        
862 #ifdef VIDEO_ENABLED    
863         LinphoneVideoPolicy vpol;
864         memset(&vpol, 0, sizeof(LinphoneVideoPolicy));
865 #endif
866         build_video_devices_table(lc);
867
868         str=lp_config_get_string(lc->config,"video","device",NULL);
869         if (str && str[0]==0) str=NULL;
870         linphone_core_set_video_device(lc,str);
871
872         linphone_core_set_preferred_video_size_by_name(lc,
873                 lp_config_get_string(lc->config,"video","size","cif"));
874
875 #ifdef VIDEO_ENABLED
876         capture=lp_config_get_int(lc->config,"video","capture",1);
877         display=lp_config_get_int(lc->config,"video","display",1);
878         self_view=lp_config_get_int(lc->config,"video","self_view",1);
879         vpol.automatically_initiate=lp_config_get_int(lc->config,"video","automatically_initiate",1);
880         vpol.automatically_accept=lp_config_get_int(lc->config,"video","automatically_accept",1);
881         lc->video_conf.displaytype=lp_config_get_string(lc->config,"video","displaytype",NULL);
882         if(lc->video_conf.displaytype)
883                 ms_message("we are using a specific display:%s\n",lc->video_conf.displaytype);
884
885         linphone_core_enable_video(lc,capture,display);
886         linphone_core_enable_video_preview(lc,lp_config_get_int(lc->config,"video","show_local",0));
887         linphone_core_enable_self_view(lc,self_view);
888         linphone_core_set_video_policy(lc,&vpol);
889 #endif
890 }
891
892 static void ui_config_read(LinphoneCore *lc)
893 {
894         LinphoneFriend *lf;
895         int i;
896         for (i=0;(lf=linphone_friend_new_from_config_file(lc,i))!=NULL;i++){
897                 linphone_core_add_friend(lc,lf);
898         }
899         call_logs_read_from_config_file(lc);
900 }
901
902 /*
903 static void autoreplier_config_init(LinphoneCore *lc)
904 {
905         autoreplier_config_t *config=&lc->autoreplier_conf;
906         config->enabled=lp_config_get_int(lc->config,"autoreplier","enabled",0);
907         config->after_seconds=lp_config_get_int(lc->config,"autoreplier","after_seconds",6);
908         config->max_users=lp_config_get_int(lc->config,"autoreplier","max_users",1);
909         config->max_rec_time=lp_config_get_int(lc->config,"autoreplier","max_rec_time",60);
910         config->max_rec_msg=lp_config_get_int(lc->config,"autoreplier","max_rec_msg",10);
911         config->message=lp_config_get_string(lc->config,"autoreplier","message",NULL);
912 }
913 */
914
915 bool_t linphone_core_tunnel_available(void){
916 #ifdef TUNNEL_ENABLED
917         return TRUE;
918 #else
919         return FALSE;
920 #endif
921 }
922
923 /**
924  * Enable adaptive rate control.
925  * 
926  * @ingroup media_parameters
927  *
928  * Adaptive rate control consists in using RTCP feedback provided information to dynamically
929  * control the output bitrate of the audio and video encoders, so that we can adapt to the network conditions and
930  * available bandwidth. Control of the audio encoder is done in case of audio-only call, and control of the video encoder is done for audio & video calls.
931  * Adaptive rate control feature is enabled by default.
932 **/
933 void linphone_core_enable_adaptive_rate_control(LinphoneCore *lc, bool_t enabled){
934         lp_config_set_int(lc->config,"net","adaptive_rate_control",(int)enabled);
935 }
936
937 /**
938  * Returns whether adaptive rate control is enabled.
939  * 
940  * @ingroup media_parameters
941  *
942  * See linphone_core_enable_adaptive_rate_control().
943 **/
944 bool_t linphone_core_adaptive_rate_control_enabled(const LinphoneCore *lc){
945         return lp_config_get_int(lc->config,"net","adaptive_rate_control",TRUE);
946 }
947
948 bool_t linphone_core_rtcp_enabled(const LinphoneCore *lc){
949         return lp_config_get_int(lc->config,"rtp","rtcp_enabled",TRUE);
950 }
951
952 /**
953  * Sets maximum available download bandwidth
954  *
955  * @ingroup media_parameters
956  *
957  * This is IP bandwidth, in kbit/s.
958  * This information is used signaled to other parties during
959  * calls (within SDP messages) so that the remote end can have
960  * sufficient knowledge to properly configure its audio & video
961  * codec output bitrate to not overflow available bandwidth.
962  *
963  * @param lc the LinphoneCore object
964  * @param bw the bandwidth in kbits/s, 0 for infinite
965  */
966 void linphone_core_set_download_bandwidth(LinphoneCore *lc, int bw){
967         lc->net_conf.download_bw=bw;
968         if (linphone_core_ready(lc)) lp_config_set_int(lc->config,"net","download_bw",bw);
969 }
970
971 /**
972  * Sets maximum available upload bandwidth
973  *
974  * @ingroup media_parameters
975  *
976  * This is IP bandwidth, in kbit/s.
977  * This information is used by liblinphone together with remote
978  * side available bandwidth signaled in SDP messages to properly
979  * configure audio & video codec's output bitrate.
980  *
981  * @param lc the LinphoneCore object
982  * @param bw the bandwidth in kbits/s, 0 for infinite
983  */
984 void linphone_core_set_upload_bandwidth(LinphoneCore *lc, int bw){
985         lc->net_conf.upload_bw=bw;
986         if (linphone_core_ready(lc)) lp_config_set_int(lc->config,"net","upload_bw",bw);
987 }
988
989 /**
990  * Retrieve the maximum available download bandwidth.
991  *
992  * @ingroup media_parameters
993  *
994  * This value was set by linphone_core_set_download_bandwidth().
995  *
996 **/
997 int linphone_core_get_download_bandwidth(const LinphoneCore *lc){
998         return lc->net_conf.download_bw;
999 }
1000
1001 /**
1002  * Retrieve the maximum available upload bandwidth.
1003  *
1004  * @ingroup media_parameters
1005  *
1006  * This value was set by linphone_core_set_upload_bandwidth().
1007  *
1008 **/
1009 int linphone_core_get_upload_bandwidth(const LinphoneCore *lc){
1010         return lc->net_conf.upload_bw;
1011 }
1012 /**
1013  * Set audio packetization time linphone expects to receive from peer.
1014  * A value of zero means that ptime is not specified.
1015  * @ingroup media_parameters
1016  */
1017 void linphone_core_set_download_ptime(LinphoneCore *lc, int ptime) {
1018         lp_config_set_int(lc->config,"rtp","download_ptime",ptime);
1019 }
1020
1021 /**
1022  * Get audio packetization time linphone expects to receive from peer.
1023  * A value of zero means that ptime is not specified.
1024  * @ingroup media_parameters
1025  */
1026 int linphone_core_get_download_ptime(LinphoneCore *lc) {
1027         return lp_config_get_int(lc->config,"rtp","download_ptime",0);
1028 }
1029
1030 /**
1031  * Set audio packetization time linphone will send (in absence of requirement from peer)
1032  * A value of 0 stands for the current codec default packetization time.
1033  *
1034  * @ingroup media_parameters
1035 **/
1036 void linphone_core_set_upload_ptime(LinphoneCore *lc, int ptime){
1037         lp_config_set_int(lc->config,"rtp","upload_ptime",ptime);
1038 }
1039
1040 /**
1041  * Set audio packetization time linphone will send (in absence of requirement from peer)
1042  * A value of 0 stands for the current codec default packetization time.
1043  *
1044  * 
1045  * @ingroup media_parameters
1046 **/
1047 int linphone_core_get_upload_ptime(LinphoneCore *lc){
1048         return lp_config_get_int(lc->config,"rtp","upload_ptime",0);
1049 }
1050
1051
1052
1053 /**
1054  * Returns liblinphone's version as a string.
1055  *
1056  * @ingroup misc
1057  *
1058 **/
1059 const char * linphone_core_get_version(void){
1060         return liblinphone_version;
1061 }
1062
1063 static void linphone_core_assign_payload_type(LinphoneCore *lc, PayloadType *const_pt, int number, const char *recv_fmtp){
1064         PayloadType *pt;
1065         pt=payload_type_clone(const_pt);
1066         if (number==-1){
1067                 /*look for a free number */
1068                 MSList *elem;
1069                 int i;
1070                 for(i=lc->dyn_pt;i<RTP_PROFILE_MAX_PAYLOADS;++i){
1071                         bool_t already_assigned=FALSE;
1072                         for(elem=lc->payload_types;elem!=NULL;elem=elem->next){
1073                                 PayloadType *it=(PayloadType*)elem->data;
1074                                 if (payload_type_get_number(it)==i){
1075                                         already_assigned=TRUE;
1076                                         break;
1077                                 }
1078                         }
1079                         if (!already_assigned){
1080                                 number=i;
1081                                 lc->dyn_pt=i+1;
1082                                 break;
1083                         }
1084                 }
1085                 if (number==-1){
1086                         ms_fatal("FIXME: too many codecs, no more free numbers.");
1087                 }
1088         }
1089         ms_message("assigning %s/%i payload type number %i",pt->mime_type,pt->clock_rate,number);
1090         payload_type_set_number(pt,number);
1091         if (recv_fmtp!=NULL) payload_type_set_recv_fmtp(pt,recv_fmtp);
1092         rtp_profile_set_payload(lc->default_profile,number,pt);
1093         lc->payload_types=ms_list_append(lc->payload_types,pt);
1094 }
1095
1096 static void linphone_core_handle_static_payloads(LinphoneCore *lc){
1097         RtpProfile *prof=&av_profile;
1098         int i;
1099         for(i=0;i<RTP_PROFILE_MAX_PAYLOADS;++i){
1100                 PayloadType *pt=rtp_profile_get_payload(prof,i);
1101                 if (pt){
1102                         if (payload_type_get_number(pt)!=i){
1103                                 linphone_core_assign_payload_type(lc,pt,i,NULL);
1104                         }
1105                 }
1106         }
1107 }
1108
1109 static void linphone_core_free_payload_types(LinphoneCore *lc){
1110         rtp_profile_clear_all(lc->default_profile);
1111         rtp_profile_destroy(lc->default_profile);
1112         ms_list_for_each(lc->payload_types,(void (*)(void*))payload_type_destroy);
1113         ms_list_free(lc->payload_types);
1114         lc->payload_types=NULL;
1115 }
1116
1117 void linphone_core_set_state(LinphoneCore *lc, LinphoneGlobalState gstate, const char *message){
1118         lc->state=gstate;
1119         if (lc->vtable.global_state_changed){
1120                 lc->vtable.global_state_changed(lc,gstate,message);
1121         }
1122 }
1123 static void misc_config_read (LinphoneCore *lc) {
1124         LpConfig *config=lc->config;
1125     lc->max_call_logs=lp_config_get_int(config,"misc","history_max_size",15);
1126     lc->max_calls=lp_config_get_int(config,"misc","max_calls",NB_MAX_CALLS);
1127 }
1128
1129
1130
1131
1132 static void linphone_core_init (LinphoneCore * lc, const LinphoneCoreVTable *vtable, const char *config_path,
1133     const char *factory_config_path, void * userdata)
1134 {
1135         ms_message("Initializing LinphoneCore %s", linphone_core_get_version());
1136         memset (lc, 0, sizeof (LinphoneCore));
1137         lc->data=userdata;
1138         lc->ringstream_autorelease=TRUE;
1139
1140         memcpy(&lc->vtable,vtable,sizeof(LinphoneCoreVTable));
1141
1142         linphone_core_set_state(lc,LinphoneGlobalStartup,"Starting up");
1143         ortp_init();
1144         lc->dyn_pt=96;
1145         lc->default_profile=rtp_profile_new("default profile");
1146         linphone_core_assign_payload_type(lc,&payload_type_pcmu8000,0,NULL);
1147         linphone_core_assign_payload_type(lc,&payload_type_gsm,3,NULL);
1148         linphone_core_assign_payload_type(lc,&payload_type_pcma8000,8,NULL);
1149         linphone_core_assign_payload_type(lc,&payload_type_speex_nb,110,"vbr=on");
1150         linphone_core_assign_payload_type(lc,&payload_type_speex_wb,111,"vbr=on");
1151         linphone_core_assign_payload_type(lc,&payload_type_speex_uwb,112,"vbr=on");
1152         linphone_core_assign_payload_type(lc,&payload_type_telephone_event,101,"0-11");
1153         linphone_core_assign_payload_type(lc,&payload_type_g722,9,NULL);
1154
1155 #if defined(ANDROID) || defined (__IPHONE_OS_VERSION_MIN_REQUIRED)
1156         /*shorten the DNS lookup time and send more retransmissions on mobiles:
1157          - to workaround potential packet losses
1158          - to avoid hanging for 30 seconds when the network doesn't work despite the phone thinks it does.
1159          */
1160         _linphone_core_configure_resolver();
1161 #endif
1162
1163 #ifdef ENABLE_NONSTANDARD_GSM
1164         {
1165                 PayloadType *pt;
1166                 pt=payload_type_clone(&payload_type_gsm);
1167                 pt->clock_rate=11025;
1168                 linphone_core_assign_payload_type(lc,pt,-1,NULL);
1169                 pt->clock_rate=22050;
1170                 linphone_core_assign_payload_type(lc,pt,-1,NULL);
1171                 payload_type_destroy(pt);
1172         }
1173 #endif
1174
1175 #ifdef VIDEO_ENABLED
1176         linphone_core_assign_payload_type(lc,&payload_type_h263,34,NULL);
1177         linphone_core_assign_payload_type(lc,&payload_type_theora,97,NULL);
1178         linphone_core_assign_payload_type(lc,&payload_type_h263_1998,98,"CIF=1;QCIF=1");
1179         linphone_core_assign_payload_type(lc,&payload_type_mp4v,99,"profile-level-id=3");
1180         linphone_core_assign_payload_type(lc,&payload_type_h264,102,"profile-level-id=428014");
1181         linphone_core_assign_payload_type(lc,&payload_type_vp8,103,NULL);
1182         linphone_core_assign_payload_type(lc,&payload_type_x_snow,-1,NULL);
1183         /* due to limited space in SDP, we have to disable this h264 line which is normally no more necessary */
1184         /* linphone_core_assign_payload_type(&payload_type_h264,-1,"packetization-mode=1;profile-level-id=428014");*/
1185 #endif
1186
1187         /*add all payload type for which we don't care about the number */
1188         linphone_core_assign_payload_type(lc,&payload_type_ilbc,-1,"mode=30");
1189         linphone_core_assign_payload_type(lc,&payload_type_amr,-1,"octet-align=1");
1190         linphone_core_assign_payload_type(lc,&payload_type_amrwb,-1,"octet-align=1");
1191         linphone_core_assign_payload_type(lc,&payload_type_lpc1015,-1,NULL);
1192         linphone_core_assign_payload_type(lc,&payload_type_g726_16,-1,NULL);
1193         linphone_core_assign_payload_type(lc,&payload_type_g726_24,-1,NULL);
1194         linphone_core_assign_payload_type(lc,&payload_type_g726_32,-1,NULL);
1195         linphone_core_assign_payload_type(lc,&payload_type_g726_40,-1,NULL);
1196         linphone_core_assign_payload_type(lc,&payload_type_aal2_g726_16,-1,NULL);
1197         linphone_core_assign_payload_type(lc,&payload_type_aal2_g726_24,-1,NULL);
1198         linphone_core_assign_payload_type(lc,&payload_type_aal2_g726_32,-1,NULL);
1199         linphone_core_assign_payload_type(lc,&payload_type_aal2_g726_40,-1,NULL);
1200         linphone_core_assign_payload_type(lc,&payload_type_silk_nb,-1,NULL);
1201         linphone_core_assign_payload_type(lc,&payload_type_silk_mb,-1,NULL);
1202         linphone_core_assign_payload_type(lc,&payload_type_silk_wb,-1,NULL);
1203         linphone_core_assign_payload_type(lc,&payload_type_silk_swb,-1,NULL);
1204         linphone_core_assign_payload_type(lc,&payload_type_g729,18,"annexb=no");
1205         linphone_core_handle_static_payloads(lc);
1206         
1207         ms_init();
1208         /* create a mediastreamer2 event queue and set it as global */
1209         /* This allows to run event's callback in linphone_core_iterate() */
1210         lc->msevq=ms_event_queue_new();
1211         ms_set_global_event_queue(lc->msevq);
1212
1213         lc->config=lp_config_new(config_path);
1214         if (factory_config_path)
1215                 lp_config_read_file(lc->config,factory_config_path);
1216
1217         lc->sal=sal_init();
1218         sal_set_user_pointer(lc->sal,lc);
1219         sal_set_callbacks(lc->sal,&linphone_sal_callbacks);
1220
1221         lc->network_last_check = 0;
1222         lc->network_last_status = FALSE;
1223
1224         sip_setup_register_all();
1225         sound_config_read(lc);
1226         net_config_read(lc);
1227         rtp_config_read(lc);
1228         codecs_config_read(lc);
1229         sip_config_read(lc); /* this will start eXosip*/
1230         video_config_read(lc);
1231         //autoreplier_config_init(&lc->autoreplier_conf);
1232         lc->presence_mode=LinphoneStatusOnline;
1233         misc_config_read(lc);
1234         ui_config_read(lc);
1235 #ifdef TUNNEL_ENABLED
1236         lc->tunnel=linphone_core_tunnel_new(lc);
1237         if (lc->tunnel) linphone_tunnel_configure(lc->tunnel);
1238 #endif
1239 #ifdef BUILD_UPNP
1240         lc->upnp = linphone_upnp_context_new(lc);
1241 #endif  //BUILD_UPNP
1242         if (lc->vtable.display_status)
1243                 lc->vtable.display_status(lc,_("Ready"));
1244         lc->auto_net_state_mon=lc->sip_conf.auto_net_state_mon;
1245         linphone_core_set_state(lc,LinphoneGlobalOn,"Ready");
1246 }
1247
1248 /**
1249  * Instanciates a LinphoneCore object.
1250  * @ingroup initializing
1251  *
1252  * The LinphoneCore object is the primary handle for doing all phone actions.
1253  * It should be unique within your application.
1254  * @param vtable a LinphoneCoreVTable structure holding your application callbacks
1255  * @param config_path a path to a config file. If it does not exists it will be created.
1256  *        The config file is used to store all settings, call logs, friends, proxies... so that all these settings
1257  *             become persistent over the life of the LinphoneCore object.
1258  *             It is allowed to set a NULL config file. In that case LinphoneCore will not store any settings.
1259  * @param factory_config_path a path to a read-only config file that can be used to
1260  *        to store hard-coded preference such as proxy settings or internal preferences.
1261  *        The settings in this factory file always override the one in the normal config file.
1262  *        It is OPTIONAL, use NULL if unneeded.
1263  * @param userdata an opaque user pointer that can be retrieved at any time (for example in
1264  *        callbacks) using linphone_core_get_user_data().
1265  *
1266 **/
1267 LinphoneCore *linphone_core_new(const LinphoneCoreVTable *vtable,
1268                                                 const char *config_path, const char *factory_config_path, void * userdata)
1269 {
1270         LinphoneCore *core=ms_new(LinphoneCore,1);
1271         linphone_core_init(core,vtable,config_path, factory_config_path, userdata);
1272         return core;
1273 }
1274
1275 /**
1276  * Returns the list of available audio codecs.
1277  *
1278  * This list is unmodifiable. The ->data field of the MSList points a PayloadType
1279  * structure holding the codec information.
1280  * It is possible to make copy of the list with ms_list_copy() in order to modify it
1281  * (such as the order of codecs).
1282  * @ingroup media_parameters
1283 **/
1284 const MSList *linphone_core_get_audio_codecs(const LinphoneCore *lc)
1285 {
1286         return lc->codecs_conf.audio_codecs;
1287 }
1288
1289 /**
1290  * Returns the list of available video codecs.
1291  *
1292  * This list is unmodifiable. The ->data field of the MSList points a PayloadType
1293  * structure holding the codec information.
1294  * It is possible to make copy of the list with ms_list_copy() in order to modify it
1295  * (such as the order of codecs).
1296  * @ingroup media_parameters
1297 **/
1298 const MSList *linphone_core_get_video_codecs(const LinphoneCore *lc)
1299 {
1300         return lc->codecs_conf.video_codecs;
1301 }
1302
1303 /**
1304  * Sets the local "from" identity.
1305  *
1306  * @ingroup proxies
1307  * This data is used in absence of any proxy configuration or when no
1308  * default proxy configuration is set. See LinphoneProxyConfig
1309 **/
1310 int linphone_core_set_primary_contact(LinphoneCore *lc, const char *contact)
1311 {
1312         LinphoneAddress *ctt;
1313
1314         if ((ctt=linphone_address_new(contact))==0) {
1315                 ms_error("Bad contact url: %s",contact);
1316                 return -1;
1317         }
1318         if (lc->sip_conf.contact!=NULL) ms_free(lc->sip_conf.contact);
1319         lc->sip_conf.contact=ms_strdup(contact);
1320         if (lc->sip_conf.guessed_contact!=NULL){
1321                 ms_free(lc->sip_conf.guessed_contact);
1322                 lc->sip_conf.guessed_contact=NULL;
1323         }
1324         linphone_address_destroy(ctt);
1325         return 0;
1326 }
1327
1328
1329 /*result must be an array of chars at least LINPHONE_IPADDR_SIZE */
1330 void linphone_core_get_local_ip(LinphoneCore *lc, const char *dest, char *result){
1331         const char *ip;
1332         if (linphone_core_get_firewall_policy(lc)==LinphonePolicyUseNatAddress
1333             && (ip=linphone_core_get_nat_address_resolved(lc))!=NULL){
1334                 strncpy(result,ip,LINPHONE_IPADDR_SIZE);
1335                 return;
1336         }
1337 #ifdef BUILD_UPNP
1338         else if (lc->upnp != NULL && linphone_core_get_firewall_policy(lc)==LinphonePolicyUseUpnp &&
1339                         linphone_upnp_context_get_state(lc->upnp) == LinphoneUpnpStateOk) {
1340                 ip = linphone_upnp_context_get_external_ipaddress(lc->upnp);
1341                 strncpy(result,ip,LINPHONE_IPADDR_SIZE);
1342                 return;
1343         }
1344 #endif  //BUILD_UPNP
1345         if (linphone_core_get_local_ip_for(lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,dest,result)==0)
1346                 return;
1347         /*else fallback to SAL routine that will attempt to find the most realistic interface */
1348         sal_get_default_local_ip(lc->sal,lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,result,LINPHONE_IPADDR_SIZE);
1349 }
1350
1351 static void update_primary_contact(LinphoneCore *lc){
1352         char *guessed=NULL;
1353         char tmp[LINPHONE_IPADDR_SIZE];
1354
1355         LinphoneAddress *url;
1356         if (lc->sip_conf.guessed_contact!=NULL){
1357                 ms_free(lc->sip_conf.guessed_contact);
1358                 lc->sip_conf.guessed_contact=NULL;
1359         }
1360         url=linphone_address_new(lc->sip_conf.contact);
1361         if (!url){
1362                 ms_error("Could not parse identity contact !");
1363                 url=linphone_address_new("sip:unknown@unkwownhost");
1364         }
1365         linphone_core_get_local_ip(lc, NULL, tmp);
1366         if (strcmp(tmp,"127.0.0.1")==0 || strcmp(tmp,"::1")==0 ){
1367                 ms_warning("Local loopback network only !");
1368                 lc->sip_conf.loopback_only=TRUE;
1369         }else lc->sip_conf.loopback_only=FALSE;
1370         linphone_address_set_domain(url,tmp);
1371         linphone_address_set_port_int(url,linphone_core_get_sip_port (lc));
1372         guessed=linphone_address_as_string(url);
1373         lc->sip_conf.guessed_contact=guessed;
1374         linphone_address_destroy(url);
1375 }
1376
1377 /**
1378  * Returns the default identity when no proxy configuration is used.
1379  *
1380  * @ingroup proxies
1381 **/
1382 const char *linphone_core_get_primary_contact(LinphoneCore *lc){
1383         char *identity;
1384
1385         if (lc->sip_conf.guess_hostname){
1386                 if (lc->sip_conf.guessed_contact==NULL || lc->sip_conf.loopback_only){
1387                         update_primary_contact(lc);
1388                 }
1389                 identity=lc->sip_conf.guessed_contact;
1390         }else{
1391                 identity=lc->sip_conf.contact;
1392         }
1393         return identity;
1394 }
1395
1396 /**
1397  * Tells LinphoneCore to guess local hostname automatically in primary contact.
1398  *
1399  * @ingroup proxies
1400 **/
1401 void linphone_core_set_guess_hostname(LinphoneCore *lc, bool_t val){
1402         lc->sip_conf.guess_hostname=val;
1403 }
1404
1405 /**
1406  * Returns TRUE if hostname part of primary contact is guessed automatically.
1407  *
1408  * @ingroup proxies
1409 **/
1410 bool_t linphone_core_get_guess_hostname(LinphoneCore *lc){
1411         return lc->sip_conf.guess_hostname;
1412 }
1413
1414 /**
1415  * Same as linphone_core_get_primary_contact() but the result is a LinphoneAddress object
1416  * instead of const char*
1417  *
1418  * @ingroup proxies
1419 **/
1420 LinphoneAddress *linphone_core_get_primary_contact_parsed(LinphoneCore *lc){
1421         return linphone_address_new(linphone_core_get_primary_contact(lc));
1422 }
1423
1424 /**
1425  * Sets the list of audio codecs.
1426  *
1427  * @ingroup media_parameters
1428  * The list is taken by the LinphoneCore thus the application should not free it.
1429  * This list is made of struct PayloadType describing the codec parameters.
1430 **/
1431 int linphone_core_set_audio_codecs(LinphoneCore *lc, MSList *codecs)
1432 {
1433         if (lc->codecs_conf.audio_codecs!=NULL) ms_list_free(lc->codecs_conf.audio_codecs);
1434         lc->codecs_conf.audio_codecs=codecs;
1435         _linphone_core_codec_config_write(lc);
1436         return 0;
1437 }
1438
1439 /**
1440  * Sets the list of video codecs.
1441  *
1442  * @ingroup media_parameters
1443  * The list is taken by the LinphoneCore thus the application should not free it.
1444  * This list is made of struct PayloadType describing the codec parameters.
1445 **/
1446 int linphone_core_set_video_codecs(LinphoneCore *lc, MSList *codecs)
1447 {
1448         if (lc->codecs_conf.video_codecs!=NULL) ms_list_free(lc->codecs_conf.video_codecs);
1449         lc->codecs_conf.video_codecs=codecs;
1450         _linphone_core_codec_config_write(lc);
1451         return 0;
1452 }
1453
1454 const MSList * linphone_core_get_friend_list(const LinphoneCore *lc)
1455 {
1456         return lc->friends;
1457 }
1458
1459 void linphone_core_enable_audio_adaptive_jittcomp(LinphoneCore* lc, bool_t val)
1460 {
1461         lc->rtp_conf.audio_adaptive_jitt_comp_enabled = val;
1462 }
1463
1464 bool_t linphone_core_audio_adaptive_jittcomp_enabled(LinphoneCore* lc)
1465 {
1466         return lc->rtp_conf.audio_adaptive_jitt_comp_enabled;
1467 }
1468
1469 /**
1470  * Returns the nominal audio jitter buffer size in milliseconds.
1471  *
1472  * @ingroup media_parameters
1473 **/
1474 int linphone_core_get_audio_jittcomp(LinphoneCore *lc)
1475 {
1476         return lc->rtp_conf.audio_jitt_comp;
1477 }
1478
1479 void linphone_core_enable_video_adaptive_jittcomp(LinphoneCore* lc, bool_t val)
1480 {
1481         lc->rtp_conf.video_adaptive_jitt_comp_enabled = val;
1482 }
1483
1484 bool_t linphone_core_video_adaptive_jittcomp_enabled(LinphoneCore* lc)
1485 {
1486         return lc->rtp_conf.video_adaptive_jitt_comp_enabled;
1487 }
1488
1489 /**
1490  * Returns the nominal video jitter buffer size in milliseconds.
1491  *
1492  * @ingroup media_parameters
1493 **/
1494 int linphone_core_get_video_jittcomp(LinphoneCore *lc)
1495 {
1496         return lc->rtp_conf.video_jitt_comp;
1497 }
1498
1499 /**
1500  * Returns the UDP port used for audio streaming.
1501  *
1502  * @ingroup network_parameters
1503 **/
1504 int linphone_core_get_audio_port(const LinphoneCore *lc)
1505 {
1506         return lc->rtp_conf.audio_rtp_min_port;
1507 }
1508
1509 /**
1510  * Get the audio port range from which is randomly chosen the UDP port used for audio streaming.
1511  *
1512  * @ingroup network_parameters
1513  */
1514 void linphone_core_get_audio_port_range(const LinphoneCore *lc, int *min_port, int *max_port)
1515 {
1516         *min_port = lc->rtp_conf.audio_rtp_min_port;
1517         *max_port = lc->rtp_conf.audio_rtp_max_port;
1518 }
1519
1520 /**
1521  * Returns the UDP port used for video streaming.
1522  *
1523  * @ingroup network_parameters
1524 **/
1525 int linphone_core_get_video_port(const LinphoneCore *lc){
1526         return lc->rtp_conf.video_rtp_min_port;
1527 }
1528
1529 /**
1530  * Get the video port range from which is randomly chosen the UDP port used for video streaming.
1531  *
1532  * @ingroup network_parameters
1533  */
1534 void linphone_core_get_video_port_range(const LinphoneCore *lc, int *min_port, int *max_port)
1535 {
1536         *min_port = lc->rtp_conf.video_rtp_min_port;
1537         *max_port = lc->rtp_conf.video_rtp_max_port;
1538 }
1539
1540
1541 /**
1542  * Returns the value in seconds of the no-rtp timeout.
1543  *
1544  * @ingroup media_parameters
1545  * When no RTP or RTCP packets have been received for a while
1546  * LinphoneCore will consider the call is broken (remote end crashed or
1547  * disconnected from the network), and thus will terminate the call.
1548  * The no-rtp timeout is the duration above which the call is considered broken.
1549 **/
1550 int linphone_core_get_nortp_timeout(const LinphoneCore *lc){
1551         return lc->rtp_conf.nortp_timeout;
1552 }
1553
1554 bool_t linphone_core_get_rtp_no_xmit_on_audio_mute(const LinphoneCore *lc){
1555         return lc->rtp_conf.rtp_no_xmit_on_audio_mute;
1556 }
1557
1558 /**
1559  * Sets the nominal audio jitter buffer size in milliseconds.
1560  *
1561  * @ingroup media_parameters
1562 **/
1563 void linphone_core_set_audio_jittcomp(LinphoneCore *lc, int value)
1564 {
1565         lc->rtp_conf.audio_jitt_comp=value;
1566 }
1567
1568 /**
1569  * Sets the nominal video jitter buffer size in milliseconds.
1570  *
1571  * @ingroup media_parameters
1572 **/
1573 void linphone_core_set_video_jittcomp(LinphoneCore *lc, int value)
1574 {
1575         lc->rtp_conf.video_jitt_comp=value;
1576 }
1577
1578 void linphone_core_set_rtp_no_xmit_on_audio_mute(LinphoneCore *lc,bool_t rtp_no_xmit_on_audio_mute){
1579         lc->rtp_conf.rtp_no_xmit_on_audio_mute=rtp_no_xmit_on_audio_mute;
1580 }
1581
1582 /**
1583  * Sets the UDP port used for audio streaming.
1584  *
1585  * @ingroup network_parameters
1586 **/
1587 void linphone_core_set_audio_port(LinphoneCore *lc, int port)
1588 {
1589         lc->rtp_conf.audio_rtp_min_port=lc->rtp_conf.audio_rtp_max_port=port;
1590 }
1591
1592 /**
1593  * Sets the UDP port range from which to randomly select the port used for audio streaming.
1594  * @ingroup media_parameters
1595  */
1596 void linphone_core_set_audio_port_range(LinphoneCore *lc, int min_port, int max_port)
1597 {
1598         lc->rtp_conf.audio_rtp_min_port=min_port;
1599         lc->rtp_conf.audio_rtp_max_port=max_port;
1600 }
1601
1602 /**
1603  * Sets the UDP port used for video streaming.
1604  *
1605  * @ingroup network_parameters
1606 **/
1607 void linphone_core_set_video_port(LinphoneCore *lc, int port){
1608         lc->rtp_conf.video_rtp_min_port=lc->rtp_conf.video_rtp_max_port=port;
1609 }
1610
1611 /**
1612  * Sets the UDP port range from which to randomly select the port used for video streaming.
1613  * @ingroup media_parameters
1614  */
1615 void linphone_core_set_video_port_range(LinphoneCore *lc, int min_port, int max_port)
1616 {
1617         lc->rtp_conf.video_rtp_min_port=min_port;
1618         lc->rtp_conf.video_rtp_max_port=max_port;
1619 }
1620
1621 /**
1622  * Sets the no-rtp timeout value in seconds.
1623  *
1624  * @ingroup media_parameters
1625  * See linphone_core_get_nortp_timeout() for details.
1626 **/
1627 void linphone_core_set_nortp_timeout(LinphoneCore *lc, int nortp_timeout){
1628         lc->rtp_conf.nortp_timeout=nortp_timeout;
1629 }
1630
1631 /**
1632  * Indicates whether SIP INFO is used for sending digits.
1633  *
1634  * @ingroup media_parameters
1635 **/
1636 bool_t linphone_core_get_use_info_for_dtmf(LinphoneCore *lc)
1637 {
1638         return lc->sip_conf.use_info;
1639 }
1640
1641 /**
1642  * Sets whether SIP INFO is to be used for sending digits.
1643  *
1644  * @ingroup media_parameters
1645 **/
1646 void linphone_core_set_use_info_for_dtmf(LinphoneCore *lc,bool_t use_info)
1647 {
1648         lc->sip_conf.use_info=use_info;
1649 }
1650
1651 /**
1652  * Indicates whether RFC2833 is used for sending digits.
1653  *
1654  * @ingroup media_parameters
1655 **/
1656 bool_t linphone_core_get_use_rfc2833_for_dtmf(LinphoneCore *lc)
1657 {
1658         return lc->sip_conf.use_rfc2833;
1659 }
1660
1661 /**
1662  * Sets whether RFC2833 is to be used for sending digits.
1663  *
1664  * @ingroup media_parameters
1665 **/
1666 void linphone_core_set_use_rfc2833_for_dtmf(LinphoneCore *lc,bool_t use_rfc2833)
1667 {
1668         lc->sip_conf.use_rfc2833=use_rfc2833;
1669 }
1670
1671 /**
1672  * Returns the UDP port used by SIP.
1673  *
1674  * Deprecated: use linphone_core_get_sip_transports() instead.
1675  * @ingroup network_parameters
1676 **/
1677 int linphone_core_get_sip_port(LinphoneCore *lc)
1678 {
1679         LCSipTransports *tr=&lc->sip_conf.transports;
1680         return tr->udp_port>0 ? tr->udp_port : (tr->tcp_port > 0 ? tr->tcp_port : tr->tls_port);
1681 }
1682
1683 static char _ua_name[64]="Linphone";
1684 static char _ua_version[64]=LINPHONE_VERSION;
1685
1686 #ifdef HAVE_EXOSIP_GET_VERSION
1687 extern const char *eXosip_get_version();
1688 #endif
1689
1690 static void apply_user_agent(LinphoneCore *lc){
1691         char ua_string[256];
1692         snprintf(ua_string,sizeof(ua_string)-1,"%s/%s (eXosip2/%s)",_ua_name,_ua_version,
1693 #ifdef HAVE_EXOSIP_GET_VERSION
1694                  eXosip_get_version()
1695 #else
1696                  "unknown"
1697 #endif
1698         );
1699         if (lc->sal) sal_set_user_agent(lc->sal,ua_string);
1700 }
1701
1702 /**
1703  * Sets the user agent string used in SIP messages.
1704  *
1705  * @ingroup misc
1706 **/
1707 void linphone_core_set_user_agent(LinphoneCore *lc, const char *name, const char *ver){
1708         strncpy(_ua_name,name,sizeof(_ua_name)-1);
1709         strncpy(_ua_version,ver,sizeof(_ua_version));
1710         apply_user_agent(lc);
1711 }
1712
1713 const char *linphone_core_get_user_agent_name(void){
1714         return _ua_name;
1715 }
1716
1717 const char *linphone_core_get_user_agent_version(void){
1718         return _ua_version;
1719 }
1720
1721 static void transport_error(LinphoneCore *lc, const char* transport, int port){
1722         char *msg=ortp_strdup_printf("Could not start %s transport on port %i, maybe this port is already used.",transport,port);
1723         ms_warning("%s",msg);
1724         if (lc->vtable.display_warning)
1725                 lc->vtable.display_warning(lc,msg);
1726         ms_free(msg);
1727 }
1728
1729 static bool_t transports_unchanged(const LCSipTransports * tr1, const LCSipTransports * tr2){
1730         return
1731                 tr2->udp_port==tr1->udp_port &&
1732                 tr2->tcp_port==tr1->tcp_port &&
1733                 tr2->dtls_port==tr1->dtls_port &&
1734                 tr2->tls_port==tr1->tls_port;
1735 }
1736
1737 static int apply_transports(LinphoneCore *lc){
1738         Sal *sal=lc->sal;
1739         const char *anyaddr;
1740         LCSipTransports *tr=&lc->sip_conf.transports;
1741
1742         /*first of all invalidate all current registrations so that we can register again with new transports*/
1743         __linphone_core_invalidate_registers(lc);
1744         
1745         if (lc->sip_conf.ipv6_enabled)
1746                 anyaddr="::0";
1747         else
1748                 anyaddr="0.0.0.0";
1749
1750         sal_unlisten_ports(sal);
1751         if (tr->udp_port>0){
1752                 if (sal_listen_port (sal,anyaddr,tr->udp_port,SalTransportUDP,FALSE)!=0){
1753                         transport_error(lc,"udp",tr->udp_port);
1754                         return -1;
1755                 }
1756         }
1757         if (tr->tcp_port>0){
1758                 if (sal_listen_port (sal,anyaddr,tr->tcp_port,SalTransportTCP,FALSE)!=0){
1759                         transport_error(lc,"tcp",tr->tcp_port);
1760                 }
1761         }
1762         if (tr->tls_port>0){
1763                 if (sal_listen_port (sal,anyaddr,tr->tls_port,SalTransportTLS,TRUE)!=0){
1764                         transport_error(lc,"tls",tr->tls_port);
1765                 }
1766         }
1767         apply_user_agent(lc);
1768         return 0;
1769 }
1770
1771 /**
1772  * Sets the ports to be used for each of transport (UDP or TCP)
1773  *
1774  * A zero value port for a given transport means the transport
1775  * is not used.
1776  *
1777  * @ingroup network_parameters
1778 **/
1779 int linphone_core_set_sip_transports(LinphoneCore *lc, const LCSipTransports * tr){
1780
1781         if (transports_unchanged(tr,&lc->sip_conf.transports))
1782                 return 0;
1783         memcpy(&lc->sip_conf.transports,tr,sizeof(*tr));
1784
1785         if (linphone_core_ready(lc)){
1786                 lp_config_set_int(lc->config,"sip","sip_port",tr->udp_port);
1787                 lp_config_set_int(lc->config,"sip","sip_tcp_port",tr->tcp_port);
1788                 lp_config_set_int(lc->config,"sip","sip_tls_port",tr->tls_port);
1789         }
1790
1791         if (lc->sal==NULL) return 0;
1792         return apply_transports(lc);
1793 }
1794
1795 /**
1796  * Retrieves the ports used for each transport (udp, tcp).
1797  * A zero value port for a given transport means the transport
1798  * is not used.
1799  * @ingroup network_parameters
1800 **/
1801 int linphone_core_get_sip_transports(LinphoneCore *lc, LCSipTransports *tr){
1802         memcpy(tr,&lc->sip_conf.transports,sizeof(*tr));
1803         return 0;
1804 }
1805
1806 /**
1807  * Sets the UDP port to be used by SIP.
1808  *
1809  * Deprecated: use linphone_core_set_sip_transports() instead.
1810  * @ingroup network_parameters
1811 **/
1812 void linphone_core_set_sip_port(LinphoneCore *lc,int port)
1813 {
1814         LCSipTransports tr;
1815         memset(&tr,0,sizeof(tr));
1816         tr.udp_port=port;
1817         linphone_core_set_sip_transports (lc,&tr);
1818 }
1819
1820 /**
1821  * Returns TRUE if IPv6 is enabled.
1822  *
1823  * @ingroup network_parameters
1824  * See linphone_core_enable_ipv6() for more details on how IPv6 is supported in liblinphone.
1825 **/
1826 bool_t linphone_core_ipv6_enabled(LinphoneCore *lc){
1827         return lc->sip_conf.ipv6_enabled;
1828 }
1829
1830 /**
1831  * Turns IPv6 support on or off.
1832  *
1833  * @ingroup network_parameters
1834  *
1835  * @note IPv6 support is exclusive with IPv4 in liblinphone:
1836  * when IPv6 is turned on, IPv4 calls won't be possible anymore.
1837  * By default IPv6 support is off.
1838 **/
1839 void linphone_core_enable_ipv6(LinphoneCore *lc, bool_t val){
1840         if (lc->sip_conf.ipv6_enabled!=val){
1841                 lc->sip_conf.ipv6_enabled=val;
1842                 if (lc->sal){
1843                         /* we need to restart eXosip */
1844                         apply_transports(lc);
1845                 }
1846         }
1847 }
1848
1849
1850 static void monitor_network_state(LinphoneCore *lc, time_t curtime){
1851         char result[LINPHONE_IPADDR_SIZE];
1852         bool_t new_status=lc->network_last_status;
1853
1854         /* only do the network up checking every five seconds */
1855         if (lc->network_last_check==0 || (curtime-lc->network_last_check)>=5){
1856                 linphone_core_get_local_ip_for(lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,NULL,result);
1857                 if (strcmp(result,"::1")!=0 && strcmp(result,"127.0.0.1")!=0){
1858                         new_status=TRUE;
1859                 }else new_status=FALSE;
1860                 lc->network_last_check=curtime;
1861                 if (new_status!=lc->network_last_status) {
1862                         if (new_status){
1863                                 ms_message("New local ip address is %s",result);
1864                         }
1865                         set_network_reachable(lc,new_status, curtime);
1866                         lc->network_last_status=new_status;
1867                 }
1868         }
1869 }
1870
1871 static void proxy_update(LinphoneCore *lc){
1872         MSList *elem,*next;
1873         ms_list_for_each(lc->sip_conf.proxies,(void (*)(void*))&linphone_proxy_config_update);
1874         for(elem=lc->sip_conf.deleted_proxies;elem!=NULL;elem=next){
1875                 LinphoneProxyConfig* cfg = (LinphoneProxyConfig*)elem->data;
1876                 next=elem->next;
1877                 if (ms_time(NULL) - cfg->deletion_date > 5) {
1878                         lc->sip_conf.deleted_proxies =ms_list_remove_link(lc->sip_conf.deleted_proxies,elem);
1879                         ms_message("clearing proxy config for [%s]",linphone_proxy_config_get_addr(cfg));
1880                         linphone_proxy_config_destroy(cfg);
1881                 }
1882         }
1883 }
1884
1885 static void assign_buddy_info(LinphoneCore *lc, BuddyInfo *info){
1886         LinphoneFriend *lf=linphone_core_get_friend_by_address(lc,info->sip_uri);
1887         if (lf!=NULL){
1888                 lf->info=info;
1889                 ms_message("%s has a BuddyInfo assigned with image %p",info->sip_uri, info->image_data);
1890                 if (lc->vtable.buddy_info_updated)
1891                         lc->vtable.buddy_info_updated(lc,lf);
1892         }else{
1893                 ms_warning("Could not any friend with uri %s",info->sip_uri);
1894         }
1895 }
1896
1897 static void analyze_buddy_lookup_results(LinphoneCore *lc, LinphoneProxyConfig *cfg){
1898         MSList *elem;
1899         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1900         for (elem=lc->bl_reqs;elem!=NULL;elem=ms_list_next(elem)){
1901                 BuddyLookupRequest *req=(BuddyLookupRequest *)elem->data;
1902                 if (req->status==BuddyLookupDone || req->status==BuddyLookupFailure){
1903                         if (req->results!=NULL){
1904                                 BuddyInfo *i=(BuddyInfo*)req->results->data;
1905                                 ms_list_free(req->results);
1906                                 req->results=NULL;
1907                                 assign_buddy_info(lc,i);
1908                         }
1909                         sip_setup_context_buddy_lookup_free(ctx,req);
1910                         elem->data=NULL;
1911                 }
1912         }
1913         /*purge completed requests */
1914         while((elem=ms_list_find(lc->bl_reqs,NULL))!=NULL){
1915                 lc->bl_reqs=ms_list_remove_link(lc->bl_reqs,elem);
1916         }
1917 }
1918
1919 static void linphone_core_grab_buddy_infos(LinphoneCore *lc, LinphoneProxyConfig *cfg){
1920         const MSList *elem;
1921         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1922         for(elem=linphone_core_get_friend_list(lc);elem!=NULL;elem=elem->next){
1923                 LinphoneFriend *lf=(LinphoneFriend*)elem->data;
1924                 if (lf->info==NULL){
1925                         if (linphone_core_lookup_known_proxy(lc,lf->uri)==cfg){
1926                                 if (linphone_address_get_username(lf->uri)!=NULL){
1927                                         BuddyLookupRequest *req;
1928                                         char *tmp=linphone_address_as_string_uri_only(lf->uri);
1929                                         req=sip_setup_context_create_buddy_lookup_request(ctx);
1930                                         buddy_lookup_request_set_key(req,tmp);
1931                                         buddy_lookup_request_set_max_results(req,1);
1932                                         sip_setup_context_buddy_lookup_submit(ctx,req);
1933                                         lc->bl_reqs=ms_list_append(lc->bl_reqs,req);
1934                                         ms_free(tmp);
1935                                 }
1936                         }
1937                 }
1938         }
1939 }
1940
1941 static void linphone_core_do_plugin_tasks(LinphoneCore *lc){
1942         LinphoneProxyConfig *cfg=NULL;
1943         linphone_core_get_default_proxy(lc,&cfg);
1944         if (cfg){
1945                 if (lc->bl_refresh){
1946                         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1947                         if (ctx && (sip_setup_context_get_capabilities(ctx) & SIP_SETUP_CAP_BUDDY_LOOKUP)){
1948                                 linphone_core_grab_buddy_infos(lc,cfg);
1949                                 lc->bl_refresh=FALSE;
1950                         }
1951                 }
1952                 if (lc->bl_reqs) analyze_buddy_lookup_results(lc,cfg);
1953         }
1954 }
1955
1956 /**
1957  * Main loop function. It is crucial that your application call it periodically.
1958  *
1959  * @ingroup initializing
1960  * linphone_core_iterate() performs various backgrounds tasks:
1961  * - receiving of SIP messages
1962  * - handles timers and timeout
1963  * - performs registration to proxies
1964  * - authentication retries
1965  * The application MUST call this function periodically, in its main loop.
1966  * Be careful that this function must be called from the same thread as
1967  * other liblinphone methods. If it is not the case make sure all liblinphone calls are
1968  * serialized with a mutex.
1969 **/
1970 void linphone_core_iterate(LinphoneCore *lc){
1971         MSList *calls;
1972         LinphoneCall *call;
1973         time_t curtime=time(NULL);
1974         int elapsed;
1975         bool_t one_second_elapsed=FALSE;
1976
1977         if (curtime-lc->prevtime>=1){
1978                 lc->prevtime=curtime;
1979                 one_second_elapsed=TRUE;
1980         }
1981
1982         if (lc->ecc!=NULL){
1983                 LinphoneEcCalibratorStatus ecs=ec_calibrator_get_status(lc->ecc);
1984                 if (ecs!=LinphoneEcCalibratorInProgress){
1985                         if (lc->ecc->cb)
1986                                 lc->ecc->cb(lc,ecs,lc->ecc->delay,lc->ecc->cb_data);
1987                         if (ecs==LinphoneEcCalibratorDone){
1988                                 int len=lp_config_get_int(lc->config,"sound","ec_tail_len",0);
1989                                 lp_config_set_int(lc->config, "sound", "ec_delay",MAX(lc->ecc->delay-(len/2),0));
1990                         } else if (ecs == LinphoneEcCalibratorFailed) {
1991                                 lp_config_set_int(lc->config, "sound", "ec_delay", LP_CONFIG_DEFAULT_INT(lc->config, "ec_delay", 250));
1992                         } else if (ecs == LinphoneEcCalibratorDoneNoEcho) {
1993                                 linphone_core_enable_echo_cancellation(lc, FALSE);
1994                         }
1995                         ec_calibrator_destroy(lc->ecc);
1996                         lc->ecc=NULL;
1997                 }
1998         }
1999
2000         if (lc->preview_finished){
2001                 lc->preview_finished=0;
2002                 ring_stop(lc->ringstream);
2003                 lc->ringstream=NULL;
2004                 lc_callback_obj_invoke(&lc->preview_finished_cb,lc);
2005         }
2006
2007         if (lc->ringstream && lc->ringstream_autorelease && lc->dmfs_playing_start_time!=0
2008             && (curtime-lc->dmfs_playing_start_time)>5){
2009                 ring_stop(lc->ringstream);
2010                 lc->ringstream=NULL;
2011                 lc->dmfs_playing_start_time=0;
2012         }
2013
2014         sal_iterate(lc->sal);
2015         if (lc->msevq) ms_event_queue_pump(lc->msevq);
2016         if (lc->auto_net_state_mon) monitor_network_state(lc,curtime);
2017
2018         proxy_update(lc);
2019
2020         //we have to iterate for each call
2021         calls= lc->calls;
2022         while(calls!= NULL){
2023                 call = (LinphoneCall *)calls->data;
2024                 elapsed = curtime-call->start_time;
2025                  /* get immediately a reference to next one in case the one
2026                  we are going to examine is destroy and removed during
2027                  linphone_core_start_invite() */
2028                 calls=calls->next;
2029                 linphone_call_background_tasks(call,one_second_elapsed);
2030                 if (call->state==LinphoneCallOutgoingInit && (curtime-call->start_time>=2)){
2031                         /*start the call even if the OPTIONS reply did not arrive*/
2032                         if (call->ice_session != NULL) {
2033                                 ms_warning("ICE candidates gathering from [%s] has not finished yet, proceed with the call without ICE anyway."
2034                                                 ,linphone_core_get_stun_server(lc));
2035                                 linphone_call_delete_ice_session(call);
2036                                 linphone_call_stop_media_streams_for_ice_gathering(call);
2037                         }
2038 #ifdef BUILD_UPNP
2039                         if (call->upnp_session != NULL) {
2040                                 ms_warning("uPnP mapping has not finished yet, proceeded with the call without uPnP anyway.");
2041                                 linphone_call_delete_upnp_session(call);
2042                         }
2043 #endif //BUILD_UPNP
2044                         linphone_core_start_invite(lc,call);
2045                 }
2046                 if (call->state==LinphoneCallIncomingReceived){
2047                         ms_message("incoming call ringing for %i seconds",elapsed);
2048                         if (elapsed>lc->sip_conf.inc_timeout){
2049                                 ms_message("incoming call timeout (%i)",lc->sip_conf.inc_timeout);
2050                                 call->log->status=LinphoneCallMissed;
2051                                 call->reason=LinphoneReasonNotAnswered;
2052                                 linphone_core_terminate_call(lc,call);
2053                         }
2054                 }
2055                 if (lc->sip_conf.in_call_timeout > 0 && elapsed>lc->sip_conf.in_call_timeout) {
2056                         ms_message("in call timeout (%i)",lc->sip_conf.in_call_timeout);
2057                         linphone_core_terminate_call(lc,call);
2058                 }
2059         }
2060                 
2061         if (linphone_core_video_preview_enabled(lc)){
2062                 if (lc->previewstream==NULL && lc->calls==NULL)
2063                         toggle_video_preview(lc,TRUE);
2064 #ifdef VIDEO_ENABLED
2065                 if (lc->previewstream) video_stream_iterate(lc->previewstream);
2066 #endif
2067         }else{
2068                 if (lc->previewstream!=NULL)
2069                         toggle_video_preview(lc,FALSE);
2070         }
2071
2072         linphone_core_run_hooks(lc);
2073         linphone_core_do_plugin_tasks(lc);
2074
2075         if (lc->initial_subscribes_sent==FALSE && lc->netup_time!=0 &&
2076             (curtime-lc->netup_time)>3){
2077                 linphone_core_send_initial_subscribes(lc);
2078                 lc->initial_subscribes_sent=TRUE;
2079         }
2080
2081         if (one_second_elapsed && lp_config_needs_commit(lc->config)){
2082                 lp_config_sync(lc->config);
2083         }
2084 }
2085
2086 /**
2087  * Interpret a call destination as supplied by the user, and returns a fully qualified
2088  * LinphoneAddress.
2089  * 
2090  * @ingroup call_control
2091  *
2092  * A sip address should look like DisplayName <sip:username@domain:port> .
2093  * Basically this function performs the following tasks
2094  * - if a phone number is entered, prepend country prefix of the default proxy
2095  *   configuration, eventually escape the '+' by 00.
2096  * - if no domain part is supplied, append the domain name of the default proxy
2097  * - if no sip: is present, prepend it
2098  *
2099  * The result is a syntaxically correct SIP address.
2100 **/
2101
2102 LinphoneAddress * linphone_core_interpret_url(LinphoneCore *lc, const char *url){
2103         enum_lookup_res_t *enumres=NULL;
2104         char *enum_domain=NULL;
2105         LinphoneProxyConfig *proxy=lc->default_proxy;;
2106         char *tmpurl;
2107         LinphoneAddress *uri;
2108
2109         if (is_enum(url,&enum_domain)){
2110                 if (lc->vtable.display_status!=NULL)
2111                         lc->vtable.display_status(lc,_("Looking for telephone number destination..."));
2112                 if (enum_lookup(enum_domain,&enumres)<0){
2113                         if (lc->vtable.display_status!=NULL)
2114                                 lc->vtable.display_status(lc,_("Could not resolve this number."));
2115                         ms_free(enum_domain);
2116                         return NULL;
2117                 }
2118                 ms_free(enum_domain);
2119                 tmpurl=enumres->sip_address[0];
2120                 uri=linphone_address_new(tmpurl);
2121                 enum_lookup_res_free(enumres);
2122                 return uri;
2123         }
2124         /* check if we have a "sip:" */
2125         if (strstr(url,"sip:")==NULL){
2126                 /* this doesn't look like a true sip uri */
2127                 if (strchr(url,'@')!=NULL){
2128                         /* seems like sip: is missing !*/
2129                         tmpurl=ms_strdup_printf("sip:%s",url);
2130                         uri=linphone_address_new(tmpurl);
2131                         ms_free(tmpurl);
2132                         if (uri){
2133                                 return uri;
2134                         }
2135                 }
2136
2137                 if (proxy!=NULL){
2138                         /* append the proxy domain suffix */
2139                         const char *identity=linphone_proxy_config_get_identity(proxy);
2140                         char normalized_username[128];
2141                         uri=linphone_address_new(identity);
2142                         if (uri==NULL){
2143                                 return NULL;
2144                         }
2145                         linphone_address_set_display_name(uri,NULL);
2146                         linphone_proxy_config_normalize_number(proxy,url,normalized_username,
2147                                                                 sizeof(normalized_username));
2148                         linphone_address_set_username(uri,normalized_username);
2149                         return uri;
2150                 }else return NULL;
2151         }
2152         uri=linphone_address_new(url);
2153         if (uri!=NULL){
2154                 return uri;
2155         }
2156         /* else we could not do anything with url given by user, so display an error */
2157         if (lc->vtable.display_warning!=NULL){
2158                 lc->vtable.display_warning(lc,_("Could not parse given sip address. A sip url usually looks like sip:user@domain"));
2159         }
2160         return NULL;
2161 }
2162
2163 /**
2164  * Returns the default identity SIP address.
2165  *
2166  * @ingroup proxies
2167  * This is an helper function:
2168  *
2169  * If no default proxy is set, this will return the primary contact (
2170  * see linphone_core_get_primary_contact() ). If a default proxy is set
2171  * it returns the registered identity on the proxy.
2172 **/
2173 const char * linphone_core_get_identity(LinphoneCore *lc){
2174         LinphoneProxyConfig *proxy=NULL;
2175         const char *from;
2176         linphone_core_get_default_proxy(lc,&proxy);
2177         if (proxy!=NULL) {
2178                 from=linphone_proxy_config_get_identity(proxy);
2179         }else from=linphone_core_get_primary_contact(lc);
2180         return from;
2181 }
2182
2183 const char * linphone_core_get_route(LinphoneCore *lc){
2184         LinphoneProxyConfig *proxy=NULL;
2185         const char *route=NULL;
2186         linphone_core_get_default_proxy(lc,&proxy);
2187         if (proxy!=NULL) {
2188                 route=linphone_proxy_config_get_route(proxy);
2189         }
2190         return route;
2191 }
2192
2193 void linphone_core_start_refered_call(LinphoneCore *lc, LinphoneCall *call){
2194         if (call->refer_pending){
2195                 LinphoneCallParams *cp=linphone_core_create_default_call_parameters(lc);
2196                 LinphoneCall *newcall;
2197                 cp->has_video &= !!lc->video_policy.automatically_initiate;
2198                 cp->referer=call;
2199                 ms_message("Starting new call to refered address %s",call->refer_to);
2200                 call->refer_pending=FALSE;
2201                 newcall=linphone_core_invite_with_params(lc,call->refer_to,cp);
2202                 linphone_call_params_destroy(cp);
2203                 if (newcall) linphone_core_notify_refer_state(lc,call,newcall);
2204         }
2205 }
2206
2207 void linphone_core_notify_refer_state(LinphoneCore *lc, LinphoneCall *referer, LinphoneCall *newcall){
2208         if (referer->op!=NULL){
2209                 sal_call_notify_refer_state(referer->op,newcall ? newcall->op : NULL);
2210         }
2211 }
2212
2213 LinphoneProxyConfig * linphone_core_lookup_known_proxy(LinphoneCore *lc, const LinphoneAddress *uri){
2214         const MSList *elem;
2215         LinphoneProxyConfig *found_cfg=NULL;
2216         LinphoneProxyConfig *default_cfg=lc->default_proxy;
2217
2218         /*always prefer the default proxy if it is matching the destination uri*/
2219         if (default_cfg){
2220                 const char *domain=linphone_proxy_config_get_domain(default_cfg);
2221                 if (strcmp(domain,linphone_address_get_domain(uri))==0)
2222                         return default_cfg;
2223         }
2224
2225         /*otherwise iterate through the other proxy config and return the first matching*/
2226         for (elem=linphone_core_get_proxy_config_list(lc);elem!=NULL;elem=elem->next){
2227                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
2228                 const char *domain=linphone_proxy_config_get_domain(cfg);
2229                 if (domain!=NULL && strcmp(domain,linphone_address_get_domain(uri))==0){
2230                         found_cfg=cfg;
2231                         break;
2232                 }
2233         }
2234         return found_cfg;
2235 }
2236
2237 const char *linphone_core_find_best_identity(LinphoneCore *lc, const LinphoneAddress *to, const char **route){
2238         LinphoneProxyConfig *cfg=linphone_core_lookup_known_proxy(lc,to);
2239         if (cfg==NULL)
2240                 linphone_core_get_default_proxy (lc,&cfg);
2241         if (cfg!=NULL){
2242                 if (route) *route=linphone_proxy_config_get_route(cfg);
2243                 return linphone_proxy_config_get_identity (cfg);
2244         }
2245         return linphone_core_get_primary_contact (lc);
2246 }
2247
2248 static char *get_fixed_contact(LinphoneCore *lc, LinphoneCall *call , LinphoneProxyConfig *dest_proxy){
2249         LinphoneAddress *ctt;
2250         const char *localip=call->localip;
2251
2252         /* first use user's supplied ip address if asked*/
2253         if (linphone_core_get_firewall_policy(lc)==LinphonePolicyUseNatAddress){
2254                 ctt=linphone_core_get_primary_contact_parsed(lc);
2255                 return ms_strdup_printf("sip:%s@%s",linphone_address_get_username(ctt),
2256                         linphone_core_get_nat_address_resolved(lc));
2257         }
2258
2259         /* if already choosed, don't change it */
2260         if (call->op && sal_op_get_contact(call->op)!=NULL){
2261                 return NULL;
2262         }
2263         /* if the ping OPTIONS request succeeded use the contact guessed from the
2264          received, rport*/
2265         if (call->ping_op){
2266                 const char *guessed=sal_op_get_contact(call->ping_op);
2267                 if (guessed){
2268                         ms_message("Contact has been fixed using OPTIONS to %s",guessed);
2269                         return ms_strdup(guessed);
2270                 }
2271         }
2272
2273         /*if using a proxy, use the contact address as guessed with the REGISTERs*/
2274         if (dest_proxy && dest_proxy->op){
2275                 const char *fixed_contact=sal_op_get_contact(dest_proxy->op);
2276                 if (fixed_contact) {
2277                         ms_message("Contact has been fixed using proxy to %s",fixed_contact);
2278                         return ms_strdup(fixed_contact);
2279                 }
2280         }
2281
2282         ctt=linphone_core_get_primary_contact_parsed(lc);
2283
2284         if (ctt!=NULL){
2285                 char *ret;
2286                 /*otherwise use supllied localip*/
2287                 linphone_address_set_domain(ctt,localip);
2288                 linphone_address_set_port_int(ctt,linphone_core_get_sip_port(lc));
2289                 ret=linphone_address_as_string_uri_only(ctt);
2290                 linphone_address_destroy(ctt);
2291                 ms_message("Contact has been fixed using local ip to %s",ret);
2292                 return ret;
2293         }
2294         return NULL;
2295 }
2296
2297 int linphone_core_proceed_with_invite_if_ready(LinphoneCore *lc, LinphoneCall *call, LinphoneProxyConfig *dest_proxy){
2298         bool_t ice_ready = FALSE;
2299         bool_t upnp_ready = FALSE;
2300         bool_t ping_ready = FALSE;
2301
2302         if (call->ice_session != NULL) {
2303                 if (ice_session_candidates_gathered(call->ice_session)) ice_ready = TRUE;
2304         } else {
2305                 ice_ready = TRUE;
2306         }
2307 #ifdef BUILD_UPNP
2308         if (call->upnp_session != NULL) {
2309                 if (linphone_upnp_session_get_state(call->upnp_session) == LinphoneUpnpStateOk) upnp_ready = TRUE;
2310         } else {
2311                 upnp_ready = TRUE;
2312         }
2313 #endif //BUILD_UPNP
2314         if (call->ping_op != NULL) {
2315                 if (call->ping_replied == TRUE) ping_ready = TRUE;
2316         } else {
2317                 ping_ready = TRUE;
2318         }
2319
2320         if ((ice_ready == TRUE) && (upnp_ready == TRUE) && (ping_ready == TRUE)) {
2321                 return linphone_core_start_invite(lc, call);
2322         }
2323         return 0;
2324 }
2325
2326 int linphone_core_start_invite(LinphoneCore *lc, LinphoneCall *call){
2327         int err;
2328         char *contact;
2329         char *real_url,*barmsg;
2330         char *from;
2331         LinphoneProxyConfig *dest_proxy=call->dest_proxy;
2332
2333         /*try to be best-effort in giving real local or routable contact address */
2334         contact=get_fixed_contact(lc,call,dest_proxy);
2335         if (contact){
2336                 sal_op_set_contact(call->op, contact);
2337                 ms_free(contact);
2338         }
2339         linphone_core_stop_dtmf_stream(lc);
2340         linphone_call_init_media_streams(call);
2341         if (lc->ringstream==NULL)
2342                 audio_stream_prepare_sound(call->audiostream,lc->sound_conf.play_sndcard,lc->sound_conf.capt_sndcard);
2343         linphone_call_make_local_media_description(lc,call);
2344         if (!lc->sip_conf.sdp_200_ack){
2345                 call->media_pending=TRUE;
2346                 sal_call_set_local_media_description(call->op,call->localdesc);
2347         }
2348         real_url=linphone_address_as_string(call->log->to);
2349         from=linphone_address_as_string(call->log->from);
2350         err=sal_call(call->op,from,real_url);
2351         call->log->call_id=ms_strdup(sal_op_get_call_id(call->op)); /*must be known at that time*/
2352
2353         if (lc->sip_conf.sdp_200_ack){
2354                 call->media_pending=TRUE;
2355                 sal_call_set_local_media_description(call->op,call->localdesc);
2356         }
2357         barmsg=ortp_strdup_printf("%s %s", _("Contacting"), real_url);
2358         if (lc->vtable.display_status!=NULL)
2359                 lc->vtable.display_status(lc,barmsg);
2360         ms_free(barmsg);
2361
2362         if (err<0){
2363                 if (lc->vtable.display_status!=NULL)
2364                         lc->vtable.display_status(lc,_("Could not call"));
2365                 linphone_call_stop_media_streams(call);
2366                 linphone_call_set_state(call,LinphoneCallError,"Call failed");
2367         }else {
2368                 linphone_call_set_state(call,LinphoneCallOutgoingProgress,"Outgoing call in progress");
2369         }
2370         ms_free(real_url);
2371         ms_free(from);
2372         return err;
2373 }
2374
2375 /**
2376  * Initiates an outgoing call
2377  *
2378  * @ingroup call_control
2379  * @param lc the LinphoneCore object
2380  * @param url the destination of the call (sip address, or phone number).
2381  *
2382  * The application doesn't own a reference to the returned LinphoneCall object.
2383  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
2384  *
2385  * @return a LinphoneCall object or NULL in case of failure
2386 **/
2387 LinphoneCall * linphone_core_invite(LinphoneCore *lc, const char *url){
2388         LinphoneCall *call;
2389         LinphoneCallParams *p=linphone_core_create_default_call_parameters (lc);
2390         p->has_video &= !!lc->video_policy.automatically_initiate;
2391         call=linphone_core_invite_with_params(lc,url,p);
2392         linphone_call_params_destroy(p);
2393         return call;
2394 }
2395
2396
2397 /**
2398  * Initiates an outgoing call according to supplied call parameters
2399  *
2400  * @ingroup call_control
2401  * @param lc the LinphoneCore object
2402  * @param url the destination of the call (sip address, or phone number).
2403  * @param p call parameters
2404  *
2405  * The application doesn't own a reference to the returned LinphoneCall object.
2406  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
2407  *
2408  * @return a LinphoneCall object or NULL in case of failure
2409 **/
2410 LinphoneCall * linphone_core_invite_with_params(LinphoneCore *lc, const char *url, const LinphoneCallParams *p){
2411         LinphoneAddress *addr=linphone_core_interpret_url(lc,url);
2412         if (addr){
2413                 LinphoneCall *call;
2414                 call=linphone_core_invite_address_with_params(lc,addr,p);
2415                 linphone_address_destroy(addr);
2416                 return call;
2417         }
2418         return NULL;
2419 }
2420
2421 /**
2422  * Initiates an outgoing call given a destination LinphoneAddress
2423  *
2424  * @ingroup call_control
2425  * @param lc the LinphoneCore object
2426  * @param addr the destination of the call (sip address).
2427  *
2428  * The LinphoneAddress can be constructed directly using linphone_address_new(), or
2429  * created by linphone_core_interpret_url().
2430  * The application doesn't own a reference to the returned LinphoneCall object.
2431  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
2432  *
2433  * @return a LinphoneCall object or NULL in case of failure
2434 **/
2435 LinphoneCall * linphone_core_invite_address(LinphoneCore *lc, const LinphoneAddress *addr){
2436         LinphoneCall *call;
2437         LinphoneCallParams *p=linphone_core_create_default_call_parameters(lc);
2438         p->has_video &= !!lc->video_policy.automatically_initiate;
2439         call=linphone_core_invite_address_with_params (lc,addr,p);
2440         linphone_call_params_destroy(p);
2441         return call;
2442 }
2443
2444
2445 /**
2446  * Initiates an outgoing call given a destination LinphoneAddress
2447  *
2448  * @ingroup call_control
2449  * @param lc the LinphoneCore object
2450  * @param addr the destination of the call (sip address).
2451         @param params call parameters
2452  *
2453  * The LinphoneAddress can be constructed directly using linphone_address_new(), or
2454  * created by linphone_core_interpret_url().
2455  * The application doesn't own a reference to the returned LinphoneCall object.
2456  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
2457  *
2458  * @return a LinphoneCall object or NULL in case of failure
2459 **/
2460 LinphoneCall * linphone_core_invite_address_with_params(LinphoneCore *lc, const LinphoneAddress *addr, const LinphoneCallParams *params)
2461 {
2462         const char *route=NULL;
2463         const char *from=NULL;
2464         LinphoneProxyConfig *proxy=NULL,*dest_proxy=NULL;
2465         LinphoneAddress *parsed_url2=NULL;
2466         char *real_url=NULL;
2467         LinphoneCall *call;
2468         bool_t defer = FALSE;
2469
2470         linphone_core_preempt_sound_resources(lc);
2471         
2472         if(!linphone_core_can_we_add_call(lc)){
2473                 if (lc->vtable.display_warning)
2474                         lc->vtable.display_warning(lc,_("Sorry, we have reached the maximum number of simultaneous calls"));
2475                 return NULL;
2476         }
2477         linphone_core_get_default_proxy(lc,&proxy);
2478         route=linphone_core_get_route(lc);
2479
2480         real_url=linphone_address_as_string(addr);
2481         dest_proxy=linphone_core_lookup_known_proxy(lc,addr);
2482
2483         if (proxy!=dest_proxy && dest_proxy!=NULL) {
2484                 ms_message("Overriding default proxy setting for this call:");
2485                 ms_message("The used identity will be %s",linphone_proxy_config_get_identity(dest_proxy));
2486         }
2487
2488         if (dest_proxy!=NULL)
2489                 from=linphone_proxy_config_get_identity(dest_proxy);
2490         else if (proxy!=NULL)
2491                 from=linphone_proxy_config_get_identity(proxy);
2492
2493         /* if no proxy or no identity defined for this proxy, default to primary contact*/
2494         if (from==NULL) from=linphone_core_get_primary_contact(lc);
2495
2496         parsed_url2=linphone_address_new(from);
2497
2498         call=linphone_call_new_outgoing(lc,parsed_url2,linphone_address_clone(addr),params);
2499         call->dest_proxy=dest_proxy;
2500         sal_op_set_route(call->op,route);
2501
2502         if(linphone_core_add_call(lc,call)!= 0)
2503         {
2504                 ms_warning("we had a problem in adding the call into the invite ... weird");
2505                 linphone_call_unref(call);
2506                 return NULL;
2507         }
2508         /* this call becomes now the current one*/
2509         lc->current_call=call;
2510         linphone_call_set_state (call,LinphoneCallOutgoingInit,"Starting outgoing call");
2511         if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseIce) {
2512                 /* Defer the start of the call after the ICE gathering process. */
2513                 linphone_call_init_media_streams(call);
2514                 linphone_call_start_media_streams_for_ice_gathering(call);
2515                 call->start_time=time(NULL);
2516                 if (linphone_core_gather_ice_candidates(lc,call)<0) {
2517                         /* Ice candidates gathering failed, proceed with the call anyway. */
2518                         linphone_call_delete_ice_session(call);
2519                         linphone_call_stop_media_streams_for_ice_gathering(call);
2520                 } else {
2521                         defer = TRUE;
2522                 }
2523         }
2524         else if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseUpnp) {
2525 #ifdef BUILD_UPNP
2526                 linphone_call_init_media_streams(call);
2527                 call->start_time=time(NULL);
2528                 if (linphone_core_update_upnp(lc,call)<0) {
2529                         /* uPnP port mappings failed, proceed with the call anyway. */
2530                         linphone_call_delete_upnp_session(call);
2531                 } else {
2532                         defer = TRUE;
2533                 }
2534 #endif //BUILD_UPNP
2535         }
2536
2537         if (call->dest_proxy==NULL && lc->sip_conf.ping_with_options==TRUE){
2538                 /*defer the start of the call after the OPTIONS ping*/
2539                 call->ping_replied=FALSE;
2540                 call->ping_op=sal_op_new(lc->sal);
2541                 sal_ping(call->ping_op,from,real_url);
2542                 sal_op_set_user_pointer(call->ping_op,call);
2543                 call->start_time=time(NULL);
2544         }else{
2545                 if (defer==FALSE) linphone_core_start_invite(lc,call);
2546         }
2547
2548         if (real_url!=NULL) ms_free(real_url);
2549         return call;
2550 }
2551
2552 /**
2553  * Performs a simple call transfer to the specified destination.
2554  *
2555  * @ingroup call_control
2556  * The remote endpoint is expected to issue a new call to the specified destination.
2557  * The current call remains active and thus can be later paused or terminated.
2558 **/
2559 int linphone_core_transfer_call(LinphoneCore *lc, LinphoneCall *call, const char *url)
2560 {
2561         char *real_url=NULL;
2562         LinphoneAddress *real_parsed_url=linphone_core_interpret_url(lc,url);
2563
2564         if (!real_parsed_url){
2565                 /* bad url */
2566                 return -1;
2567         }
2568         if (call==NULL){
2569                 ms_warning("No established call to refer.");
2570                 return -1;
2571         }
2572         //lc->call=NULL; //Do not do that you will lose the call afterward . . .
2573         real_url=linphone_address_as_string (real_parsed_url);
2574         sal_call_refer(call->op,real_url);
2575         ms_free(real_url);
2576         linphone_address_destroy(real_parsed_url);
2577         linphone_call_set_transfer_state(call, LinphoneCallOutgoingInit);
2578         return 0;
2579 }
2580
2581 /**
2582  * Transfer a call to destination of another running call. This is used for "attended transfer" scenarios.
2583  * @param lc linphone core object
2584  * @param call a running call you want to transfer
2585  * @param dest a running call whose remote person will receive the transfer
2586  * 
2587  * @ingroup call_control
2588  *
2589  * The transfered call is supposed to be in paused state, so that it is able to accept the transfer immediately.
2590  * The destination call is a call previously established to introduce the transfered person.
2591  * This method will send a transfer request to the transfered person. The phone of the transfered is then
2592  * expected to automatically call to the destination of the transfer. The receiver of the transfer will then automatically
2593  * close the call with us (the 'dest' call).
2594 **/
2595 int linphone_core_transfer_call_to_another(LinphoneCore *lc, LinphoneCall *call, LinphoneCall *dest){
2596         int result = sal_call_refer_with_replaces (call->op,dest->op);
2597         linphone_call_set_transfer_state(call, LinphoneCallOutgoingInit);
2598         return result;
2599 }
2600
2601 bool_t linphone_core_inc_invite_pending(LinphoneCore*lc){
2602         LinphoneCall *call = linphone_core_get_current_call(lc);
2603         if(call != NULL)
2604         {
2605                 if(call->dir==LinphoneCallIncoming
2606                         && (call->state == LinphoneCallIncomingReceived || call->state ==  LinphoneCallIncomingEarlyMedia))
2607                         return TRUE;
2608         }
2609         return FALSE;
2610 }
2611
2612 bool_t linphone_core_incompatible_security(LinphoneCore *lc, SalMediaDescription *md){
2613         if (linphone_core_is_media_encryption_mandatory(lc) && linphone_core_get_media_encryption(lc)==LinphoneMediaEncryptionSRTP){
2614                 int i;
2615                 for(i=0;i<md->n_active_streams;i++){
2616                         SalStreamDescription *sd=&md->streams[i];
2617                         if (sd->proto!=SalProtoRtpSavp){
2618                                 return TRUE;
2619                         }
2620                 }
2621         }
2622         return FALSE;
2623 }
2624
2625 void linphone_core_notify_incoming_call(LinphoneCore *lc, LinphoneCall *call){
2626         char *barmesg;
2627         char *tmp;
2628         LinphoneAddress *from_parsed;
2629         SalMediaDescription *md;
2630         bool_t propose_early_media=lp_config_get_int(lc->config,"sip","incoming_calls_early_media",FALSE);
2631         const char *ringback_tone=linphone_core_get_remote_ringback_tone (lc);
2632
2633         linphone_call_make_local_media_description(lc,call);
2634         sal_call_set_local_media_description(call->op,call->localdesc);
2635         md=sal_call_get_final_media_description(call->op);
2636         if (md){
2637                 if (sal_media_description_empty(md) || linphone_core_incompatible_security(lc,md)){
2638                         sal_call_decline(call->op,SalReasonMedia,NULL);
2639                         linphone_call_unref(call);
2640                         return;
2641                 }
2642         }
2643
2644         from_parsed=linphone_address_new(sal_op_get_from(call->op));
2645         linphone_address_clean(from_parsed);
2646         tmp=linphone_address_as_string(from_parsed);
2647         linphone_address_destroy(from_parsed);
2648         barmesg=ortp_strdup_printf("%s %s%s",tmp,_("is contacting you"),
2649             (sal_call_autoanswer_asked(call->op)) ?_(" and asked autoanswer."):_("."));
2650         if (lc->vtable.show) lc->vtable.show(lc);
2651         if (lc->vtable.display_status)
2652             lc->vtable.display_status(lc,barmesg);
2653
2654         /* play the ring if this is the only call*/
2655         if (ms_list_size(lc->calls)==1){
2656                 lc->current_call=call;
2657                 if (lc->ringstream && lc->dmfs_playing_start_time!=0){
2658                         ring_stop(lc->ringstream);
2659                         lc->ringstream=NULL;
2660                         lc->dmfs_playing_start_time=0;
2661                 }
2662                 if (lc->sound_conf.ring_sndcard!=NULL){
2663                         if(lc->ringstream==NULL && lc->sound_conf.local_ring){
2664                                 MSSndCard *ringcard=lc->sound_conf.lsd_card ?lc->sound_conf.lsd_card : lc->sound_conf.ring_sndcard;
2665                                 ms_message("Starting local ring...");
2666                                 lc->ringstream=ring_start(lc->sound_conf.local_ring,2000,ringcard);
2667                         }
2668                         else
2669                         {
2670                                 ms_message("the local ring is already started");
2671                         }
2672                 }
2673         }else{
2674                 /* else play a tone within the context of the current call */
2675                 call->ringing_beep=TRUE;
2676                 linphone_core_play_tone(lc);
2677         }
2678
2679         linphone_call_set_state(call,LinphoneCallIncomingReceived,"Incoming call");
2680
2681         if (call->state==LinphoneCallIncomingReceived){
2682                 sal_call_notify_ringing(call->op,propose_early_media || ringback_tone!=NULL);
2683
2684                 if (propose_early_media || ringback_tone!=NULL){
2685                         linphone_call_set_state(call,LinphoneCallIncomingEarlyMedia,"Incoming call early media");
2686                         md=sal_call_get_final_media_description(call->op);
2687                         linphone_core_update_streams(lc,call,md);
2688                 }
2689                 if (sal_call_get_replaces(call->op)!=NULL && lp_config_get_int(lc->config,"sip","auto_answer_replacing_calls",1)){
2690                         linphone_core_accept_call(lc,call);
2691                 }
2692         }
2693         linphone_call_unref(call);
2694
2695         ms_free(barmesg);
2696         ms_free(tmp);
2697 }
2698
2699 int linphone_core_start_update_call(LinphoneCore *lc, LinphoneCall *call){
2700         const char *subject;
2701         call->camera_active=call->params.has_video;
2702         if (call->ice_session != NULL) {
2703                 linphone_core_update_local_media_description_from_ice(call->localdesc, call->ice_session);
2704         }
2705 #ifdef BUILD_UPNP
2706         if(call->upnp_session != NULL) {
2707                 linphone_core_update_local_media_description_from_upnp(call->localdesc, call->upnp_session);
2708         }
2709 #endif //BUILD_UPNP
2710         if (call->params.in_conference){
2711                 subject="Conference";
2712         }else{
2713                 subject="Media change";
2714         }
2715         if (lc->vtable.display_status)
2716                 lc->vtable.display_status(lc,_("Modifying call parameters..."));
2717         sal_call_set_local_media_description (call->op,call->localdesc);
2718         return sal_call_update(call->op,subject);
2719 }
2720
2721 /**
2722  * @ingroup call_control
2723  * Updates a running call according to supplied call parameters or parameters changed in the LinphoneCore.
2724  *
2725  * In this version this is limited to the following use cases:
2726  * - setting up/down the video stream according to the video parameter of the LinphoneCallParams (see linphone_call_params_enable_video() ).
2727  * - changing the size of the transmitted video after calling linphone_core_set_preferred_video_size()
2728  *
2729  * In case no changes are requested through the LinphoneCallParams argument, then this argument can be omitted and set to NULL.
2730  * @param lc the core
2731  * @param call the call to be updated
2732  * @param params the new call parameters to use. (may be NULL)
2733  * @return 0 if successful, -1 otherwise.
2734 **/
2735 int linphone_core_update_call(LinphoneCore *lc, LinphoneCall *call, const LinphoneCallParams *params){
2736         int err=0;
2737         if (params!=NULL){
2738                 linphone_call_set_state(call,LinphoneCallUpdating,"Updating call");
2739 #ifdef VIDEO_ENABLED
2740                 bool_t has_video = call->params.has_video;
2741
2742                 // Video removing
2743                 if((call->videostream != NULL) && !params->has_video) {
2744                         if (call->ice_session != NULL) {
2745                                 ice_session_remove_check_list(call->ice_session, call->videostream->ms.ice_check_list);
2746                                 call->videostream->ms.ice_check_list = NULL;
2747                         }
2748 #ifdef BUILD_UPNP
2749                         if(call->upnp_session != NULL) {
2750                                 if (linphone_core_update_upnp(lc, call)<0) {
2751                                         /* uPnP port mappings failed, proceed with the call anyway. */
2752                                         linphone_call_delete_upnp_session(call);
2753                                 }
2754                         }
2755 #endif //BUILD_UPNP
2756                 }
2757
2758                 call->params = *params;
2759                 linphone_call_make_local_media_description(lc, call);
2760
2761                 // Video adding
2762                 if (!has_video && call->params.has_video) {
2763                         if (call->ice_session != NULL) {
2764                                 /* Defer call update until the ICE candidates gathering process has finished. */
2765                                 ms_message("Defer call update to gather ICE candidates");
2766                                 linphone_call_init_video_stream(call);
2767                                 video_stream_prepare_video(call->videostream);
2768                                 if (linphone_core_gather_ice_candidates(lc,call)<0) {
2769                                         /* Ice candidates gathering failed, proceed with the call anyway. */
2770                                         linphone_call_delete_ice_session(call);
2771                                 } else {
2772                                         return err;
2773                                 }
2774                         }
2775 #ifdef BUILD_UPNP
2776                         if(call->upnp_session != NULL) {
2777                                 ms_message("Defer call update to add uPnP port mappings");
2778                                 linphone_call_init_video_stream(call);
2779                                 video_stream_prepare_video(call->videostream);
2780                                 if (linphone_core_update_upnp(lc, call)<0) {
2781                                         /* uPnP port mappings failed, proceed with the call anyway. */
2782                                         linphone_call_delete_upnp_session(call);
2783                                 } else {
2784                                         return err;
2785                                 }
2786                         }
2787 #endif //BUILD_UPNP
2788                 }
2789 #endif
2790                 err = linphone_core_start_update_call(lc, call);
2791         }else{
2792 #ifdef VIDEO_ENABLED
2793                 if (call->videostream!=NULL){
2794                         video_stream_set_sent_video_size(call->videostream,linphone_core_get_preferred_video_size(lc));
2795                         if (call->camera_active && call->videostream->cam!=lc->video_conf.device){
2796                                 video_stream_change_camera(call->videostream,lc->video_conf.device);
2797                         }else video_stream_update_video_params(call->videostream);
2798                 }
2799 #endif
2800         }
2801
2802         return err;
2803 }
2804
2805 /**
2806  * @ingroup call_control
2807  * When receiving a #LinphoneCallUpdatedByRemote state notification, prevent LinphoneCore from performing an automatic answer.
2808  * 
2809  * When receiving a #LinphoneCallUpdatedByRemote state notification (ie an incoming reINVITE), the default behaviour of
2810  * LinphoneCore is to automatically answer the reINIVTE with call parameters unchanged.
2811  * However when for example when the remote party updated the call to propose a video stream, it can be useful
2812  * to prompt the user before answering. This can be achieved by calling linphone_core_defer_call_update() during 
2813  * the call state notifiacation, to deactivate the automatic answer that would just confirm the audio but reject the video.
2814  * Then, when the user responds to dialog prompt, it becomes possible to call linphone_core_accept_call_update() to answer
2815  * the reINVITE, with eventually video enabled in the LinphoneCallParams argument.
2816  * 
2817  * @return 0 if successful, -1 if the linphone_core_defer_call_update() was done outside a #LinphoneCallUpdatedByRemote notification, which is illegal.
2818 **/
2819 int linphone_core_defer_call_update(LinphoneCore *lc, LinphoneCall *call){
2820         if (call->state==LinphoneCallUpdatedByRemote){
2821                 call->defer_update=TRUE;
2822                 return 0;
2823         }
2824         ms_error("linphone_core_defer_call_update() not done in state LinphoneCallUpdatedByRemote");
2825         return -1;
2826 }
2827
2828 int linphone_core_start_accept_call_update(LinphoneCore *lc, LinphoneCall *call){
2829         SalMediaDescription *md;
2830         if (call->ice_session != NULL) {
2831                 if (ice_session_nb_losing_pairs(call->ice_session) > 0) {
2832                         /* Defer the sending of the answer until there are no losing pairs left. */
2833                         return 0;
2834                 }
2835                 linphone_core_update_local_media_description_from_ice(call->localdesc, call->ice_session);
2836         }
2837 #ifdef BUILD_UPNP
2838         if(call->upnp_session != NULL) {
2839                 linphone_core_update_local_media_description_from_upnp(call->localdesc, call->upnp_session);
2840         }
2841 #endif //BUILD_UPNP
2842         linphone_call_update_remote_session_id_and_ver(call);
2843         sal_call_set_local_media_description(call->op,call->localdesc);
2844         sal_call_accept(call->op);
2845         md=sal_call_get_final_media_description(call->op);
2846         if (md && !sal_media_description_empty(md))
2847                 linphone_core_update_streams (lc,call,md);
2848         linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
2849         return 0;
2850 }
2851
2852 /**
2853  * @ingroup call_control
2854  * Accept call modifications initiated by other end.
2855  * 
2856  * This call may be performed in response to a #LinphoneCallUpdatedByRemote state notification.
2857  * When such notification arrives, the application can decide to call linphone_core_defer_update_call() so that it can
2858  * have the time to prompt the user. linphone_call_get_remote_params() can be used to get information about the call parameters
2859  * requested by the other party, such as whether a video stream is requested.
2860  * 
2861  * When the user accepts or refuse the change, linphone_core_accept_call_update() can be done to answer to the other party.
2862  * If params is NULL, then the same call parameters established before the update request will continue to be used (no change).
2863  * If params is not NULL, then the update will be accepted according to the parameters passed.
2864  * Typical example is when a user accepts to start video, then params should indicate that video stream should be used 
2865  * (see linphone_call_params_enable_video()).
2866  * @param lc the linphone core object.
2867  * @param call the LinphoneCall object
2868  * @param params a LinphoneCallParams object describing the call parameters to accept.
2869  * @return 0 if sucessful, -1 otherwise (actually when this function call is performed outside ot #LinphoneCallUpdatedByRemote state).
2870 **/
2871 int linphone_core_accept_call_update(LinphoneCore *lc, LinphoneCall *call, const LinphoneCallParams *params){
2872         SalMediaDescription *remote_desc;
2873         bool_t keep_sdp_version;
2874 #ifdef VIDEO_ENABLED
2875         bool_t old_has_video = call->params.has_video;
2876 #endif
2877         if (call->state!=LinphoneCallUpdatedByRemote){
2878                 ms_error("linphone_core_accept_update(): invalid state %s to call this function.",
2879                          linphone_call_state_to_string(call->state));
2880                 return -1;
2881         }
2882         remote_desc = sal_call_get_remote_media_description(call->op);
2883         keep_sdp_version = lp_config_get_int(lc->config, "sip", "keep_sdp_version", 0);
2884         if (keep_sdp_version &&(remote_desc->session_id == call->remote_session_id) && (remote_desc->session_ver == call->remote_session_ver)) {
2885                 /* Remote has sent an INVITE with the same SDP as before, so send a 200 OK with the same SDP as before. */
2886                 ms_warning("SDP version has not changed, send same SDP as before.");
2887                 sal_call_accept(call->op);
2888                 linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
2889                 return 0;
2890         }
2891         if (params==NULL){
2892                 call->params.has_video=lc->video_policy.automatically_accept || call->current_params.has_video;
2893         }else
2894                 call->params=*params;
2895
2896         if (call->params.has_video && !linphone_core_video_enabled(lc)){
2897                 ms_warning("linphone_core_accept_call_update(): requested video but video support is globally disabled. Refusing video.");
2898                 call->params.has_video=FALSE;
2899         }
2900         if (call->current_params.in_conference) {
2901                 ms_warning("Video isn't supported in conference");
2902                 call->params.has_video = FALSE;
2903         }
2904         call->params.has_video &= linphone_core_media_description_contains_video_stream(remote_desc);
2905         call->camera_active=call->params.has_video;
2906         linphone_call_make_local_media_description(lc,call);
2907         if (call->ice_session != NULL) {
2908                 linphone_core_update_ice_from_remote_media_description(call, remote_desc);
2909 #ifdef VIDEO_ENABLED
2910                 if ((call->ice_session != NULL) &&!ice_session_candidates_gathered(call->ice_session)) {
2911                         if ((call->params.has_video) && (call->params.has_video != old_has_video)) {
2912                                 linphone_call_init_video_stream(call);
2913                                 video_stream_prepare_video(call->videostream);
2914                                 if (linphone_core_gather_ice_candidates(lc,call)<0) {
2915                                         /* Ice candidates gathering failed, proceed with the call anyway. */
2916                                         linphone_call_delete_ice_session(call);
2917                                 } else return 0;
2918                         }
2919                 }
2920 #endif //VIDEO_ENABLED
2921         }
2922
2923 #if BUILD_UPNP
2924         if(call->upnp_session != NULL) {
2925                 linphone_core_update_upnp_from_remote_media_description(call, sal_call_get_remote_media_description(call->op));
2926 #ifdef VIDEO_ENABLED
2927                 if ((call->params.has_video) && (call->params.has_video != old_has_video)) {
2928                         linphone_call_init_video_stream(call);
2929                         video_stream_prepare_video(call->videostream);
2930                         if (linphone_core_update_upnp(lc, call)<0) {
2931                                 /* uPnP update failed, proceed with the call anyway. */
2932                                 linphone_call_delete_upnp_session(call);
2933                         } else return 0;
2934                 }
2935 #endif //VIDEO_ENABLED
2936         }
2937 #endif //BUILD_UPNP
2938
2939         linphone_core_start_accept_call_update(lc, call);
2940         return 0;
2941 }
2942
2943 /**
2944  * Accept an incoming call.
2945  *
2946  * @ingroup call_control
2947  * Basically the application is notified of incoming calls within the
2948  * call_state_changed callback of the #LinphoneCoreVTable structure, where it will receive
2949  * a LinphoneCallIncoming event with the associated LinphoneCall object.
2950  * The application can later accept the call using this method.
2951  * @param lc the LinphoneCore object
2952  * @param call the LinphoneCall object representing the call to be answered.
2953  *
2954 **/
2955 int linphone_core_accept_call(LinphoneCore *lc, LinphoneCall *call){
2956         return linphone_core_accept_call_with_params(lc,call,NULL);
2957 }
2958
2959 /**
2960  * Accept an incoming call, with parameters.
2961  *
2962  * @ingroup call_control
2963  * Basically the application is notified of incoming calls within the
2964  * call_state_changed callback of the #LinphoneCoreVTable structure, where it will receive
2965  * a LinphoneCallIncoming event with the associated LinphoneCall object.
2966  * The application can later accept the call using
2967  * this method.
2968  * @param lc the LinphoneCore object
2969  * @param call the LinphoneCall object representing the call to be answered.
2970  * @param params the specific parameters for this call, for example whether video is accepted or not. Use NULL to use default parameters.
2971  *
2972 **/
2973 int linphone_core_accept_call_with_params(LinphoneCore *lc, LinphoneCall *call, const LinphoneCallParams *params)
2974 {
2975         LinphoneProxyConfig *cfg=NULL;
2976         const char *contact=NULL;
2977         SalOp *replaced;
2978         SalMediaDescription *new_md;
2979         bool_t was_ringing=FALSE;
2980
2981         if (call==NULL){
2982                 //if just one call is present answer the only one ...
2983                 if(linphone_core_get_calls_nb (lc) != 1)
2984                         return -1;
2985                 else
2986                         call = (LinphoneCall*)linphone_core_get_calls(lc)->data;
2987         }
2988
2989         if (call->state==LinphoneCallConnected){
2990                 /*call already accepted*/
2991                 return -1;
2992         }
2993
2994         /* check if this call is supposed to replace an already running one*/
2995         replaced=sal_call_get_replaces(call->op);
2996         if (replaced){
2997                 LinphoneCall *rc=(LinphoneCall*)sal_op_get_user_pointer (replaced);
2998                 if (rc){
2999                         ms_message("Call %p replaces call %p. This last one is going to be terminated automatically.",
3000                                    call,rc);
3001                         linphone_core_terminate_call(lc,rc);
3002                 }
3003         }
3004
3005         if (lc->current_call!=call){
3006                 linphone_core_preempt_sound_resources(lc);
3007         }
3008
3009         /*stop ringing */
3010         if (lc->ringstream!=NULL) {
3011                 ms_message("stop ringing");
3012                 ring_stop(lc->ringstream);
3013                 ms_message("ring stopped");
3014                 lc->ringstream=NULL;
3015                 was_ringing=TRUE;
3016         }
3017         if (call->ringing_beep){
3018                 linphone_core_stop_dtmf(lc);
3019                 call->ringing_beep=FALSE;
3020         }
3021
3022         linphone_core_get_default_proxy(lc,&cfg);
3023         call->dest_proxy=cfg;
3024         call->dest_proxy=linphone_core_lookup_known_proxy(lc,call->log->to);
3025
3026         if (cfg!=call->dest_proxy && call->dest_proxy!=NULL) {
3027                 ms_message("Overriding default proxy setting for this call:");
3028                 ms_message("The used identity will be %s",linphone_proxy_config_get_identity(call->dest_proxy));
3029         }
3030         /*try to be best-effort in giving real local or routable contact address*/
3031         contact=get_fixed_contact(lc,call,call->dest_proxy);
3032         if (contact)
3033                 sal_op_set_contact(call->op,contact);
3034
3035         if (params){
3036                 const SalMediaDescription *md = sal_call_get_remote_media_description(call->op);
3037                 _linphone_call_params_copy(&call->params,params);
3038                 // There might not be a md if the INVITE was lacking an SDP
3039                 // In this case we use the parameters as is.
3040                 if (md) call->params.has_video &= linphone_core_media_description_contains_video_stream(md);
3041                 call->camera_active=call->params.has_video;
3042                 linphone_call_make_local_media_description(lc,call);
3043                 sal_call_set_local_media_description(call->op,call->localdesc);
3044         }
3045         
3046         if (call->audiostream==NULL)
3047                 linphone_call_init_media_streams(call);
3048         if (!was_ringing && call->audiostream->ms.ticker==NULL){
3049                 audio_stream_prepare_sound(call->audiostream,lc->sound_conf.play_sndcard,lc->sound_conf.capt_sndcard);
3050         }
3051
3052         linphone_call_update_remote_session_id_and_ver(call);
3053         sal_call_accept(call->op);
3054         if (lc->vtable.display_status!=NULL)
3055                 lc->vtable.display_status(lc,_("Connected."));
3056         lc->current_call=call;
3057         linphone_call_set_state(call,LinphoneCallConnected,"Connected");
3058         new_md=sal_call_get_final_media_description(call->op);
3059         linphone_core_update_streams(lc, call, new_md);
3060         if (new_md){
3061                 linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
3062         }else call->media_pending=TRUE;
3063
3064         ms_message("call answered.");
3065         return 0;
3066 }
3067
3068 int linphone_core_abort_call(LinphoneCore *lc, LinphoneCall *call, const char *error){
3069         sal_call_terminate(call->op);
3070
3071         /*stop ringing*/
3072         if (lc->ringstream!=NULL) {
3073                 ring_stop(lc->ringstream);
3074                 lc->ringstream=NULL;
3075         }
3076         linphone_call_stop_media_streams(call);
3077
3078 #ifdef BUILD_UPNP
3079         linphone_call_delete_upnp_session(call);
3080 #endif //BUILD_UPNP
3081
3082         if (lc->vtable.display_status!=NULL)
3083                 lc->vtable.display_status(lc,_("Call aborted") );
3084         linphone_call_set_state(call,LinphoneCallError,error);
3085         return 0;
3086 }
3087
3088 static void terminate_call(LinphoneCore *lc, LinphoneCall *call){
3089         if (call->state==LinphoneCallIncomingReceived){
3090                 if (call->reason!=LinphoneReasonNotAnswered)
3091                         call->reason=LinphoneReasonDeclined;
3092         }
3093         /*stop ringing*/
3094         if (lc->ringstream!=NULL) {
3095                 ring_stop(lc->ringstream);
3096                 lc->ringstream=NULL;
3097         }
3098
3099         linphone_call_stop_media_streams(call);
3100
3101 #ifdef BUILD_UPNP
3102         linphone_call_delete_upnp_session(call);
3103 #endif //BUILD_UPNP
3104
3105         if (lc->vtable.display_status!=NULL)
3106                 lc->vtable.display_status(lc,_("Call ended") );
3107         linphone_call_set_state(call,LinphoneCallEnd,"Call terminated");
3108 }
3109
3110 int linphone_core_redirect_call(LinphoneCore *lc, LinphoneCall *call, const char *redirect_uri){
3111         if (call->state==LinphoneCallIncomingReceived){
3112                 sal_call_decline(call->op,SalReasonRedirect,redirect_uri);
3113                 call->reason=LinphoneReasonDeclined;
3114                 terminate_call(lc,call);
3115         }else{
3116                 ms_error("Bad state for call redirection.");
3117                 return -1;
3118     }
3119         return 0;
3120 }
3121
3122
3123 /**
3124  * Terminates a call.
3125  *
3126  * @ingroup call_control
3127  * @param lc the LinphoneCore
3128  * @param the_call the LinphoneCall object representing the call to be terminated.
3129 **/
3130 int linphone_core_terminate_call(LinphoneCore *lc, LinphoneCall *the_call)
3131 {
3132         LinphoneCall *call;
3133         if (the_call == NULL){
3134                 call = linphone_core_get_current_call(lc);
3135                 if (ms_list_size(lc->calls)==1){
3136                         call=(LinphoneCall*)lc->calls->data;
3137                 }else{
3138                         ms_warning("No unique call to terminate !");
3139                         return -1;
3140                 }
3141         }
3142         else
3143         {
3144                 call = the_call;
3145         }
3146         sal_call_terminate(call->op);
3147         terminate_call(lc,call);
3148         return 0;
3149 }
3150
3151 /**
3152  * Decline a pending incoming call, with a reason.
3153  * 
3154  * @ingroup call_control
3155  * 
3156  * @param lc the linphone core
3157  * @param call the LinphoneCall, must be in the IncomingReceived state.
3158  * @param reason the reason for rejecting the call: LinphoneReasonDeclined or LinphoneReasonBusy
3159 **/
3160 int linphone_core_decline_call(LinphoneCore *lc, LinphoneCall * call, LinphoneReason reason){
3161         SalReason sal_reason=SalReasonUnknown;
3162         if (call->state!=LinphoneCallIncomingReceived && call->state!=LinphoneCallIncomingEarlyMedia){
3163                 ms_error("linphone_core_decline_call(): Cannot decline a call that is in state %s",linphone_call_state_to_string(call->state));
3164                 return -1;
3165         }
3166         switch(reason){
3167                 case LinphoneReasonDeclined:
3168                         sal_reason=SalReasonDeclined;
3169                 break;
3170                 case LinphoneReasonBusy:
3171                         sal_reason=SalReasonBusy;
3172                 break;
3173                 default:
3174                         ms_error("linphone_core_decline_call(): unsupported reason %s",linphone_reason_to_string(reason));
3175                         return -1;
3176                 break;
3177         }
3178         sal_call_decline(call->op,sal_reason,NULL);
3179         terminate_call(lc,call);
3180         return 0;
3181 }
3182
3183 /**
3184  * Terminates all the calls.
3185  *
3186  * @ingroup call_control
3187  * @param lc The LinphoneCore
3188 **/
3189 int linphone_core_terminate_all_calls(LinphoneCore *lc){
3190         MSList *calls=lc->calls;
3191         while(calls) {
3192                 LinphoneCall *c=(LinphoneCall*)calls->data;
3193                 calls=calls->next;
3194                 linphone_core_terminate_call(lc,c);
3195         }
3196         return 0;
3197 }
3198
3199 /**
3200  * Returns the current list of calls.
3201  *
3202  * Note that this list is read-only and might be changed by the core after a function call to linphone_core_iterate().
3203  * Similarly the LinphoneCall objects inside it might be destroyed without prior notice.
3204  * To hold references to LinphoneCall object into your program, you must use linphone_call_ref().
3205  *
3206  * @ingroup call_control
3207 **/
3208 const MSList *linphone_core_get_calls(LinphoneCore *lc)
3209 {
3210         return lc->calls;
3211 }
3212
3213 /**
3214  * Returns TRUE if there is a call running.
3215  *
3216  * @ingroup call_control
3217 **/
3218 bool_t linphone_core_in_call(const LinphoneCore *lc){
3219         return linphone_core_get_current_call((LinphoneCore *)lc)!=NULL || linphone_core_is_in_conference(lc);
3220 }
3221
3222 /**
3223  * Returns The _LinphoneCall struct of the current call if one is in call
3224  *
3225  * @ingroup call_control
3226 **/
3227 LinphoneCall *linphone_core_get_current_call(const LinphoneCore *lc)
3228 {
3229         return lc->current_call;
3230 }
3231
3232 /**
3233  * Pauses the call. If a music file has been setup using linphone_core_set_play_file(),
3234  * this file will be played to the remote user.
3235  *
3236  * @ingroup call_control
3237 **/
3238 int linphone_core_pause_call(LinphoneCore *lc, LinphoneCall *call)
3239 {
3240         const char *subject=NULL;
3241
3242         if (call->state!=LinphoneCallStreamsRunning && call->state!=LinphoneCallPausedByRemote){
3243                 ms_warning("Cannot pause this call, it is not active.");
3244                 return -1;
3245         }
3246         linphone_call_make_local_media_description(lc,call);
3247         if (call->ice_session != NULL) {
3248                 linphone_core_update_local_media_description_from_ice(call->localdesc, call->ice_session);
3249         }
3250 #ifdef BUILD_UPNP
3251         if(call->upnp_session != NULL) {
3252                 linphone_core_update_local_media_description_from_upnp(call->localdesc, call->upnp_session);
3253         }
3254 #endif //BUILD_UPNP
3255         if (sal_media_description_has_dir(call->resultdesc,SalStreamSendRecv)){
3256                 sal_media_description_set_dir(call->localdesc,SalStreamSendOnly);
3257                 subject="Call on hold";
3258         }else if (sal_media_description_has_dir(call->resultdesc,SalStreamRecvOnly)){
3259                 sal_media_description_set_dir(call->localdesc,SalStreamSendOnly);
3260                 subject="Call on hold for me too";
3261         }else{
3262                 ms_error("No reason to pause this call, it is already paused or inactive.");
3263                 return -1;
3264         }
3265         sal_call_set_local_media_description(call->op,call->localdesc);
3266         if (sal_call_update(call->op,subject) != 0){
3267                 if (lc->vtable.display_warning)
3268                         lc->vtable.display_warning(lc,_("Could not pause the call"));
3269         }
3270         lc->current_call=NULL;
3271         linphone_call_set_state(call,LinphoneCallPausing,"Pausing call");
3272         if (lc->vtable.display_status)
3273                 lc->vtable.display_status(lc,_("Pausing the current call..."));
3274         if (call->audiostream || call->videostream)
3275                 linphone_call_stop_media_streams (call);
3276         return 0;
3277 }
3278
3279 /**
3280  * Pause all currently running calls.
3281  * @ingroup call_control
3282 **/
3283 int linphone_core_pause_all_calls(LinphoneCore *lc){
3284         const MSList *elem;
3285         for(elem=lc->calls;elem!=NULL;elem=elem->next){
3286                 LinphoneCall *call=(LinphoneCall *)elem->data;
3287                 LinphoneCallState cs=linphone_call_get_state(call);
3288                 if (cs==LinphoneCallStreamsRunning || cs==LinphoneCallPausedByRemote){
3289                         linphone_core_pause_call(lc,call);
3290                 }
3291         }
3292         return 0;
3293 }
3294
3295 void linphone_core_preempt_sound_resources(LinphoneCore *lc){
3296         LinphoneCall *current_call;
3297         if (linphone_core_is_in_conference(lc)){
3298                 linphone_core_leave_conference(lc);
3299                 return;
3300         }
3301         current_call=linphone_core_get_current_call(lc);
3302         if(current_call != NULL){
3303                 ms_message("Pausing automatically the current call.");
3304                 linphone_core_pause_call(lc,current_call);
3305         }
3306 }
3307
3308 /**
3309  * Resumes the call.
3310  *
3311  * @ingroup call_control
3312 **/
3313 int linphone_core_resume_call(LinphoneCore *lc, LinphoneCall *the_call)
3314 {
3315         char temp[255]={0};
3316         LinphoneCall *call = the_call;
3317         const char *subject="Call resuming";
3318         
3319         if(call->state!=LinphoneCallPaused ){
3320                 ms_warning("we cannot resume a call that has not been established and paused before");
3321                 return -1;
3322         }
3323         if (call->params.in_conference==FALSE){
3324                 linphone_core_preempt_sound_resources(lc);
3325                 ms_message("Resuming call %p",call);
3326         }
3327
3328         /* Stop playing music immediately. If remote side is a conference it
3329          prevents the participants to hear it while the 200OK comes back.*/
3330         if (call->audiostream) audio_stream_play(call->audiostream, NULL);
3331
3332         linphone_call_make_local_media_description(lc,the_call);
3333         if (call->ice_session != NULL) {
3334                 linphone_core_update_local_media_description_from_ice(call->localdesc, call->ice_session);
3335         }
3336 #ifdef BUILD_UPNP
3337         if(call->upnp_session != NULL) {
3338                 linphone_core_update_local_media_description_from_upnp(call->localdesc, call->upnp_session);
3339         }
3340 #endif //BUILD_UPNP
3341         sal_call_set_local_media_description(call->op,call->localdesc);
3342         sal_media_description_set_dir(call->localdesc,SalStreamSendRecv);
3343         if (call->params.in_conference && !call->current_params.in_conference) subject="Conference";
3344         if(sal_call_update(call->op,subject) != 0){
3345                 return -1;
3346         }
3347         linphone_call_set_state (call,LinphoneCallResuming,"Resuming");
3348         snprintf(temp,sizeof(temp)-1,"Resuming the call with %s",linphone_call_get_remote_address_as_string(call));
3349         if (lc->vtable.display_status)
3350                 lc->vtable.display_status(lc,temp);
3351         return 0;
3352 }
3353
3354 static int remote_address_compare(LinphoneCall *call, const LinphoneAddress *raddr){
3355         const LinphoneAddress *addr=linphone_call_get_remote_address (call);
3356         return !linphone_address_weak_equal (addr,raddr);
3357 }
3358
3359 /**
3360  * Get the call with the remote_address specified
3361  * @param lc
3362  * @param remote_address
3363  * @return the LinphoneCall of the call if found
3364  * 
3365  * @ingroup call_control
3366  */
3367 LinphoneCall *linphone_core_get_call_by_remote_address(LinphoneCore *lc, const char *remote_address){
3368         LinphoneAddress *raddr=linphone_address_new(remote_address);
3369         MSList *elem=ms_list_find_custom(lc->calls,(int (*)(const void*,const void *))remote_address_compare,raddr);
3370         if (elem) return (LinphoneCall*) elem->data;
3371         return NULL;
3372 }
3373
3374 int linphone_core_send_publish(LinphoneCore *lc,
3375                                LinphoneOnlineStatus presence_mode)
3376 {
3377         const MSList *elem;
3378         for (elem=linphone_core_get_proxy_config_list(lc);elem!=NULL;elem=ms_list_next(elem)){
3379                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
3380                 if (cfg->publish) linphone_proxy_config_send_publish(cfg,presence_mode);
3381         }
3382         return 0;
3383 }
3384
3385 /**
3386  * Set the incoming call timeout in seconds.
3387  *
3388  * @ingroup call_control
3389  * If an incoming call isn't answered for this timeout period, it is
3390  * automatically declined.
3391 **/
3392 void linphone_core_set_inc_timeout(LinphoneCore *lc, int seconds){
3393         lc->sip_conf.inc_timeout=seconds;
3394         if (linphone_core_ready(lc)){
3395                 lp_config_set_int(lc->config,"sip","inc_timeout",seconds);
3396         }
3397 }
3398
3399 /**
3400  * Returns the incoming call timeout
3401  *
3402  * @ingroup call_control
3403  * See linphone_core_set_inc_timeout() for details.
3404 **/
3405 int linphone_core_get_inc_timeout(LinphoneCore *lc){
3406         return lc->sip_conf.inc_timeout;
3407 }
3408
3409 /**
3410  * Set the in call timeout in seconds.
3411  *
3412  * @ingroup call_control
3413  * After this timeout period, the call is automatically hangup.
3414 **/
3415 void linphone_core_set_in_call_timeout(LinphoneCore *lc, int seconds){
3416         lc->sip_conf.in_call_timeout=seconds;
3417 }
3418
3419 /**
3420  * Returns the in call timeout
3421  *
3422  * @ingroup call_control
3423  * See linphone_core_set_in_call_timeout() for details.
3424 **/
3425 int linphone_core_get_in_call_timeout(LinphoneCore *lc){
3426         return lc->sip_conf.in_call_timeout;
3427 }
3428
3429 void linphone_core_set_presence_info(LinphoneCore *lc,int minutes_away,
3430                                                                                                         const char *contact,
3431                                                                                                         LinphoneOnlineStatus presence_mode)
3432 {
3433         if (minutes_away>0) lc->minutes_away=minutes_away;
3434
3435         if (lc->alt_contact!=NULL) {
3436                 ms_free(lc->alt_contact);
3437                 lc->alt_contact=NULL;
3438         }
3439         if (contact) lc->alt_contact=ms_strdup(contact);
3440         if (lc->presence_mode!=presence_mode){
3441                 linphone_core_notify_all_friends(lc,presence_mode);
3442                 /*
3443                    Improve the use of all LINPHONE_STATUS available.
3444                    !TODO Do not mix "presence status" with "answer status code"..
3445                    Use correct parameter to follow sip_if_match/sip_etag.
3446                  */
3447                 linphone_core_send_publish(lc,presence_mode);
3448         }
3449         lc->presence_mode=presence_mode;
3450 }
3451
3452 LinphoneOnlineStatus linphone_core_get_presence_info(const LinphoneCore *lc){
3453         return lc->presence_mode;
3454 }
3455
3456 /**
3457  * Get playback sound level in 0-100 scale.
3458  *
3459  * @ingroup media_parameters
3460 **/
3461 int linphone_core_get_play_level(LinphoneCore *lc)
3462 {
3463         return lc->sound_conf.play_lev;
3464 }
3465
3466 /**
3467  * Get ring sound level in 0-100 scale
3468  *
3469  * @ingroup media_parameters
3470 **/
3471 int linphone_core_get_ring_level(LinphoneCore *lc)
3472 {
3473         return lc->sound_conf.ring_lev;
3474 }
3475
3476 /**
3477  * Get sound capture level in 0-100 scale
3478  *
3479  * @ingroup media_parameters
3480 **/
3481 int linphone_core_get_rec_level(LinphoneCore *lc){
3482         return lc->sound_conf.rec_lev;
3483 }
3484
3485 /**
3486  * Set sound ring level in 0-100 scale
3487  *
3488  * @ingroup media_parameters
3489 **/
3490 void linphone_core_set_ring_level(LinphoneCore *lc, int level){
3491         MSSndCard *sndcard;
3492         lc->sound_conf.ring_lev=level;
3493         sndcard=lc->sound_conf.ring_sndcard;
3494         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_PLAYBACK,level);
3495 }
3496
3497 /**
3498  * Allow to control microphone level:  gain in db
3499  *
3500  * @ingroup media_parameters
3501 **/
3502 void linphone_core_set_mic_gain_db (LinphoneCore *lc, float gaindb){
3503         float gain=gaindb;
3504         LinphoneCall *call=linphone_core_get_current_call (lc);
3505         AudioStream *st;
3506
3507         lc->sound_conf.soft_mic_lev=gaindb;
3508
3509         if (linphone_core_ready(lc)){
3510                 lp_config_set_float(lc->config,"sound","mic_gain_db",lc->sound_conf.soft_mic_lev);
3511         }
3512
3513         if (call==NULL || (st=call->audiostream)==NULL){
3514                 ms_message("linphone_core_set_mic_gain_db(): no active call.");
3515                 return;
3516         }
3517         if (st->volrecv){
3518                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_DB_GAIN,&gain);
3519         }else ms_warning("Could not apply gain: gain control wasn't activated.");
3520 }
3521
3522 /**
3523  * Get microphone gain in db.
3524  *
3525  * @ingroup media_parameters
3526 **/
3527 float linphone_core_get_mic_gain_db(LinphoneCore *lc) {
3528         return lc->sound_conf.soft_mic_lev;
3529 }
3530
3531 /**
3532  * Allow to control play level before entering sound card:  gain in db
3533  *
3534  * @ingroup media_parameters
3535 **/
3536 void linphone_core_set_playback_gain_db (LinphoneCore *lc, float gaindb){
3537         float gain=gaindb;
3538         LinphoneCall *call=linphone_core_get_current_call (lc);
3539         AudioStream *st;
3540
3541         lc->sound_conf.soft_play_lev=gaindb;
3542         if (linphone_core_ready(lc)){
3543                 lp_config_set_float(lc->config,"sound","playback_gain_db",lc->sound_conf.soft_play_lev);
3544         }
3545
3546         if (call==NULL || (st=call->audiostream)==NULL){
3547                 ms_message("linphone_core_set_playback_gain_db(): no active call.");
3548                 return;
3549         }
3550         if (st->volrecv){
3551                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_DB_GAIN,&gain);
3552         }else ms_warning("Could not apply gain: gain control wasn't activated.");
3553 }
3554
3555 /**
3556  * Get playback gain in db before entering  sound card.
3557  *
3558  * @ingroup media_parameters
3559 **/
3560 float linphone_core_get_playback_gain_db(LinphoneCore *lc) {
3561         return lc->sound_conf.soft_play_lev;
3562 }
3563
3564 /**
3565  * Set sound playback level in 0-100 scale
3566  *
3567  * @ingroup media_parameters
3568 **/
3569 void linphone_core_set_play_level(LinphoneCore *lc, int level){
3570         MSSndCard *sndcard;
3571         lc->sound_conf.play_lev=level;
3572         sndcard=lc->sound_conf.play_sndcard;
3573         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_PLAYBACK,level);
3574 }
3575
3576 /**
3577  * Set sound capture level in 0-100 scale
3578  *
3579  * @ingroup media_parameters
3580 **/
3581 void linphone_core_set_rec_level(LinphoneCore *lc, int level)
3582 {
3583         MSSndCard *sndcard;
3584         lc->sound_conf.rec_lev=level;
3585         sndcard=lc->sound_conf.capt_sndcard;
3586         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_CAPTURE,level);
3587 }
3588
3589 static MSSndCard *get_card_from_string_id(const char *devid, unsigned int cap){
3590         MSSndCard *sndcard=NULL;
3591         if (devid!=NULL){
3592                 sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
3593                 if (sndcard!=NULL &&
3594                         (ms_snd_card_get_capabilities(sndcard) & cap)==0 ){
3595                         ms_warning("%s card does not have the %s capability, ignoring.",
3596                                 devid,
3597                                 cap==MS_SND_CARD_CAP_CAPTURE ? "capture" : "playback");
3598                         sndcard=NULL;
3599                 }
3600         }
3601         if (sndcard==NULL) {
3602                 /* get a card that has read+write capabilities */
3603                 sndcard=ms_snd_card_manager_get_default_card(ms_snd_card_manager_get());
3604                 /* otherwise refine to the first card having the right capability*/
3605                 if (sndcard==NULL){
3606                         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
3607                         for(;elem!=NULL;elem=elem->next){
3608                                 sndcard=(MSSndCard*)elem->data;
3609                                 if (ms_snd_card_get_capabilities(sndcard) & cap) break;
3610                         }
3611                 }
3612                 if (sndcard==NULL){/*looks like a bug! take the first one !*/
3613                         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
3614                         if (elem) sndcard=(MSSndCard*)elem->data;
3615         }
3616         }
3617         if (sndcard==NULL) ms_error("Could not find a suitable soundcard !");
3618         return sndcard;
3619 }
3620
3621 /**
3622  * Returns true if the specified sound device can capture sound.
3623  *
3624  * @ingroup media_parameters
3625  * @param lc The LinphoneCore object
3626  * @param devid the device name as returned by linphone_core_get_sound_devices()
3627 **/
3628 bool_t linphone_core_sound_device_can_capture(LinphoneCore *lc, const char *devid){
3629         MSSndCard *sndcard;
3630         sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
3631         if (sndcard!=NULL && (ms_snd_card_get_capabilities(sndcard) & MS_SND_CARD_CAP_CAPTURE)) return TRUE;
3632         return FALSE;
3633 }
3634
3635 /**
3636  * Returns true if the specified sound device can play sound.
3637  *
3638  * @ingroup media_parameters
3639  * @param lc The LinphoneCore object
3640  * @param devid the device name as returned by linphone_core_get_sound_devices()
3641 **/
3642 bool_t linphone_core_sound_device_can_playback(LinphoneCore *lc, const char *devid){
3643         MSSndCard *sndcard;
3644         sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
3645         if (sndcard!=NULL && (ms_snd_card_get_capabilities(sndcard) & MS_SND_CARD_CAP_PLAYBACK)) return TRUE;
3646         return FALSE;
3647 }
3648
3649 /**
3650  * Sets the sound device used for ringing.
3651  *
3652  * @ingroup media_parameters
3653  * @param lc The LinphoneCore object
3654  * @param devid the device name as returned by linphone_core_get_sound_devices()
3655 **/
3656 int linphone_core_set_ringer_device(LinphoneCore *lc, const char * devid){
3657         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_PLAYBACK);
3658         lc->sound_conf.ring_sndcard=card;
3659         if (card && linphone_core_ready(lc))
3660                 lp_config_set_string(lc->config,"sound","ringer_dev_id",ms_snd_card_get_string_id(card));
3661         return 0;
3662 }
3663
3664 /**
3665  * Sets the sound device used for playback.
3666  *
3667  * @ingroup media_parameters
3668  * @param lc The LinphoneCore object
3669  * @param devid the device name as returned by linphone_core_get_sound_devices()
3670 **/
3671 int linphone_core_set_playback_device(LinphoneCore *lc, const char * devid){
3672         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_PLAYBACK);
3673         lc->sound_conf.play_sndcard=card;
3674         if (card &&  linphone_core_ready(lc))
3675                 lp_config_set_string(lc->config,"sound","playback_dev_id",ms_snd_card_get_string_id(card));
3676         return 0;
3677 }
3678
3679 /**
3680  * Sets the sound device used for capture.
3681  *
3682  * @ingroup media_parameters
3683  * @param lc The LinphoneCore object
3684  * @param devid the device name as returned by linphone_core_get_sound_devices()
3685 **/
3686 int linphone_core_set_capture_device(LinphoneCore *lc, const char * devid){
3687         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_CAPTURE);
3688         lc->sound_conf.capt_sndcard=card;
3689         if (card &&  linphone_core_ready(lc))
3690                 lp_config_set_string(lc->config,"sound","capture_dev_id",ms_snd_card_get_string_id(card));
3691         return 0;
3692 }
3693
3694 /**
3695  * Returns the name of the currently assigned sound device for ringing.
3696  *
3697  * @ingroup media_parameters
3698  * @param lc The LinphoneCore object
3699 **/
3700 const char * linphone_core_get_ringer_device(LinphoneCore *lc)
3701 {
3702         if (lc->sound_conf.ring_sndcard) return ms_snd_card_get_string_id(lc->sound_conf.ring_sndcard);
3703         return NULL;
3704 }
3705
3706 /**
3707  * Returns the name of the currently assigned sound device for playback.
3708  *
3709  * @ingroup media_parameters
3710  * @param lc The LinphoneCore object
3711 **/
3712 const char * linphone_core_get_playback_device(LinphoneCore *lc)
3713 {
3714         return lc->sound_conf.play_sndcard ? ms_snd_card_get_string_id(lc->sound_conf.play_sndcard) : NULL;
3715 }
3716
3717 /**
3718  * Returns the name of the currently assigned sound device for capture.
3719  *
3720  * @ingroup media_parameters
3721  * @param lc The LinphoneCore object
3722 **/
3723 const char * linphone_core_get_capture_device(LinphoneCore *lc)
3724 {
3725         return lc->sound_conf.capt_sndcard ? ms_snd_card_get_string_id(lc->sound_conf.capt_sndcard) : NULL;
3726 }
3727
3728 /**
3729  * Returns an unmodifiable array of available sound devices.
3730  *
3731  * The array is NULL terminated.
3732  *
3733  * @ingroup media_parameters
3734  * @param lc The LinphoneCore object
3735 **/
3736 const char**  linphone_core_get_sound_devices(LinphoneCore *lc){
3737         return lc->sound_conf.cards;
3738 }
3739
3740 /**
3741  * Returns an unmodifiable array of available video capture devices.
3742  *
3743  * @ingroup media_parameters
3744  * The array is NULL terminated.
3745 **/
3746 const char**  linphone_core_get_video_devices(const LinphoneCore *lc){
3747         return lc->video_conf.cams;
3748 }
3749
3750 /**
3751  * Update detection of sound devices.
3752  * 
3753  * Use this function when the application is notified of USB plug events, so that
3754  * list of available hardwares for sound playback and capture is updated.
3755  **/
3756 void linphone_core_reload_sound_devices(LinphoneCore *lc){
3757         const char *ringer,*playback,*capture;
3758         ringer=linphone_core_get_ringer_device(lc);
3759         playback=linphone_core_get_playback_device(lc);
3760         capture=linphone_core_get_capture_device(lc);
3761         ms_snd_card_manager_reload(ms_snd_card_manager_get());
3762         build_sound_devices_table(lc);
3763         linphone_core_set_ringer_device(lc,ringer);
3764         linphone_core_set_playback_device(lc,playback);
3765         linphone_core_set_capture_device(lc,capture);
3766 }
3767
3768 /**
3769  * Update detection of camera devices.
3770  * 
3771  * Use this function when the application is notified of USB plug events, so that
3772  * list of available hardwares for video capture is updated.
3773  **/
3774 void linphone_core_reload_video_devices(LinphoneCore *lc){
3775         const char *devid;
3776         devid=linphone_core_get_video_device(lc);
3777         ms_web_cam_manager_reload(ms_web_cam_manager_get());
3778         build_video_devices_table(lc);
3779         linphone_core_set_video_device(lc,devid);
3780 }
3781
3782 char linphone_core_get_sound_source(LinphoneCore *lc)
3783 {
3784         return lc->sound_conf.source;
3785 }
3786
3787 void linphone_core_set_sound_source(LinphoneCore *lc, char source)
3788 {
3789         MSSndCard *sndcard=lc->sound_conf.capt_sndcard;
3790         lc->sound_conf.source=source;
3791         if (!sndcard) return;
3792         switch(source){
3793                 case 'm':
3794                         ms_snd_card_set_capture(sndcard,MS_SND_CARD_MIC);
3795                         break;
3796                 case 'l':
3797                         ms_snd_card_set_capture(sndcard,MS_SND_CARD_LINE);
3798                         break;
3799         }
3800
3801 }
3802
3803
3804 /**
3805  * Sets the path to a wav file used for ringing.
3806  *
3807  * @param path The file must be a wav 16bit linear. Local ring is disabled if null
3808  * @param lc The LinphoneCore object
3809  *
3810  * @ingroup media_parameters
3811 **/
3812 void linphone_core_set_ring(LinphoneCore *lc,const char *path){
3813         if (lc->sound_conf.local_ring!=0){
3814                 ms_free(lc->sound_conf.local_ring);
3815                 lc->sound_conf.local_ring=NULL;
3816         }
3817         if (path)
3818                 lc->sound_conf.local_ring=ms_strdup(path);
3819         if ( linphone_core_ready(lc) && lc->sound_conf.local_ring)
3820                 lp_config_set_string(lc->config,"sound","local_ring",lc->sound_conf.local_ring);
3821 }
3822
3823 /**
3824  * Returns the path to the wav file used for ringing.
3825  *
3826  * @param lc The LinphoneCore object
3827  * @ingroup media_parameters
3828 **/
3829 const char *linphone_core_get_ring(const LinphoneCore *lc){
3830         return lc->sound_conf.local_ring;
3831 }
3832
3833 /**
3834  * Sets the path to a file or folder containing trusted root CAs (PEM format)
3835  *
3836  * @param path
3837  * @param lc The LinphoneCore object
3838  *
3839  * @ingroup initializing
3840 **/
3841 void linphone_core_set_root_ca(LinphoneCore *lc,const char *path){
3842         sal_set_root_ca(lc->sal, path);
3843 }
3844
3845 /**
3846  * Gets the path to a file or folder containing the trusted root CAs (PEM format)
3847  *
3848  * @param lc The LinphoneCore object
3849  *
3850  * @ingroup initializing
3851 **/
3852 const char *linphone_core_get_root_ca(LinphoneCore *lc){
3853         return sal_get_root_ca(lc->sal);
3854 }
3855
3856 /**
3857  * Specify whether the tls server certificate must be verified when connecting to a SIP/TLS server.
3858  * 
3859  * @ingroup initializing
3860 **/
3861 void linphone_core_verify_server_certificates(LinphoneCore *lc, bool_t yesno){
3862         sal_verify_server_certificates(lc->sal,yesno);
3863 }
3864
3865 /**
3866  * Specify whether the tls server certificate common name must be verified when connecting to a SIP/TLS server.
3867  * @ingroup initializing
3868 **/
3869 void linphone_core_verify_server_cn(LinphoneCore *lc, bool_t yesno){
3870         sal_verify_server_cn(lc->sal,yesno);
3871 }
3872
3873 static void notify_end_of_ring(void *ud, MSFilter *f, unsigned int event, void *arg){
3874         LinphoneCore *lc=(LinphoneCore*)ud;
3875         lc->preview_finished=1;
3876 }
3877
3878 int linphone_core_preview_ring(LinphoneCore *lc, const char *ring,LinphoneCoreCbFunc func,void * userdata)
3879 {
3880         if (lc->ringstream!=0){
3881                 ms_warning("Cannot start ring now,there's already a ring being played");
3882                 return -1;
3883         }
3884         lc_callback_obj_init(&lc->preview_finished_cb,func,userdata);
3885         lc->preview_finished=0;
3886         if (lc->sound_conf.ring_sndcard!=NULL){
3887                 MSSndCard *ringcard=lc->sound_conf.lsd_card ? lc->sound_conf.lsd_card : lc->sound_conf.ring_sndcard;
3888                 lc->ringstream=ring_start_with_cb(ring,2000,ringcard,notify_end_of_ring,(void *)lc);
3889         }
3890         return 0;
3891 }
3892
3893 /**
3894  * Sets the path to a wav file used for ringing back.
3895  *
3896  * Ringback means the ring that is heard when it's ringing at the remote party.
3897  * The file must be a wav 16bit linear.
3898  *
3899  * @ingroup media_parameters
3900 **/
3901 void linphone_core_set_ringback(LinphoneCore *lc, const char *path){
3902         if (lc->sound_conf.remote_ring!=0){
3903                 ms_free(lc->sound_conf.remote_ring);
3904         }
3905         lc->sound_conf.remote_ring=ms_strdup(path);
3906 }
3907
3908 /**
3909  * Returns the path to the wav file used for ringing back.
3910  *
3911  * @ingroup media_parameters
3912 **/
3913 const char * linphone_core_get_ringback(const LinphoneCore *lc){
3914         return lc->sound_conf.remote_ring;
3915 }
3916
3917 /**
3918  * Enables or disable echo cancellation. Value is saved an used for subsequent calls
3919  *
3920  * @ingroup media_parameters
3921 **/
3922 void linphone_core_enable_echo_cancellation(LinphoneCore *lc, bool_t val){
3923         lc->sound_conf.ec=val;
3924         if ( linphone_core_ready(lc))
3925                 lp_config_set_int(lc->config,"sound","echocancellation",val);
3926 }
3927
3928
3929 /**
3930  * Returns TRUE if echo cancellation is enabled.
3931  *
3932  * @ingroup media_parameters
3933 **/
3934 bool_t linphone_core_echo_cancellation_enabled(LinphoneCore *lc){
3935         return lc->sound_conf.ec;
3936 }
3937
3938 void linphone_core_enable_echo_limiter(LinphoneCore *lc, bool_t val){
3939         lc->sound_conf.ea=val;
3940 }
3941
3942 bool_t linphone_core_echo_limiter_enabled(const LinphoneCore *lc){
3943         return lc->sound_conf.ea;
3944 }
3945
3946 /**
3947  * Mutes or unmutes the local microphone.
3948  *
3949  * @ingroup media_parameters
3950 **/
3951 void linphone_core_mute_mic(LinphoneCore *lc, bool_t val){
3952         LinphoneCall *call=linphone_core_get_current_call(lc);
3953         AudioStream *st=NULL;
3954         if (linphone_core_is_in_conference(lc)){
3955                 lc->conf_ctx.local_muted=val;
3956                 st=lc->conf_ctx.local_participant;
3957         }else if (call==NULL){
3958                 ms_warning("linphone_core_mute_mic(): No current call !");
3959                 return;
3960         }else{
3961                 st=call->audiostream;
3962                 call->audio_muted=val;
3963         }
3964         if (st!=NULL){
3965                 audio_stream_set_mic_gain(st,
3966                         (val==TRUE) ? 0 : pow(10,lc->sound_conf.soft_mic_lev/10));
3967                 if ( linphone_core_get_rtp_no_xmit_on_audio_mute(lc) ){
3968                         audio_stream_mute_rtp(st,val);
3969                 }
3970                 
3971         }
3972 }
3973 /**
3974  * Returns whether microphone is muted.
3975 **/
3976 bool_t linphone_core_is_mic_muted(LinphoneCore *lc) {
3977         LinphoneCall *call=linphone_core_get_current_call(lc);
3978         if (linphone_core_is_in_conference(lc)){
3979                 return lc->conf_ctx.local_muted;
3980         }else if (call==NULL){
3981                 ms_warning("linphone_core_is_mic_muted(): No current call !");
3982                 return FALSE;
3983         }
3984         return call->audio_muted;
3985 }
3986
3987 // returns rtp transmission status for an active stream
3988 // if audio is muted and config parameter rtp_no_xmit_on_audio_mute
3989 // was set on then rtp transmission is also muted
3990 bool_t linphone_core_is_rtp_muted(LinphoneCore *lc){
3991         LinphoneCall *call=linphone_core_get_current_call(lc);
3992         if (call==NULL){
3993                 ms_warning("linphone_core_is_mic_muted(): No current call !");
3994                 return FALSE;
3995         }
3996         if( linphone_core_get_rtp_no_xmit_on_audio_mute(lc)){
3997                 return call->audio_muted;
3998         }
3999         return FALSE;
4000 }
4001
4002 void linphone_core_enable_agc(LinphoneCore *lc, bool_t val){
4003         lc->sound_conf.agc=val;
4004 }
4005
4006 bool_t linphone_core_agc_enabled(const LinphoneCore *lc){
4007         return lc->sound_conf.agc;
4008 }
4009
4010 /**
4011  * Send the specified dtmf.
4012  *
4013  * @ingroup media_parameters
4014  * This function only works during calls. The dtmf is automatically played to the user.
4015  * @param lc The LinphoneCore object
4016  * @param dtmf The dtmf name specified as a char, such as '0', '#' etc...
4017  *
4018 **/
4019 void linphone_core_send_dtmf(LinphoneCore *lc, char dtmf)
4020 {
4021         LinphoneCall *call=linphone_core_get_current_call(lc);
4022         if (call==NULL){
4023                 ms_warning("linphone_core_send_dtmf(): no active call");
4024                 return;
4025         }
4026         /*By default we send DTMF RFC2833 if we do not have enabled SIP_INFO but we can also send RFC2833 and SIP_INFO*/
4027         if (linphone_core_get_use_rfc2833_for_dtmf(lc)!=0 || linphone_core_get_use_info_for_dtmf(lc)==0)
4028         {
4029                 /* In Band DTMF */
4030                 if (call->audiostream!=NULL){
4031                         audio_stream_send_dtmf(call->audiostream,dtmf);
4032                 }
4033                 else
4034                 {
4035                         ms_error("we cannot send RFC2833 dtmf when we are not in communication");
4036                 }
4037         }
4038         if (linphone_core_get_use_info_for_dtmf(lc)!=0){
4039                 /* Out of Band DTMF (use INFO method) */
4040                 sal_call_send_dtmf(call->op,dtmf);
4041         }
4042 }
4043
4044 void linphone_core_set_stun_server(LinphoneCore *lc, const char *server){
4045         if (lc->net_conf.stun_server!=NULL)
4046                 ms_free(lc->net_conf.stun_server);
4047         if (server)
4048                 lc->net_conf.stun_server=ms_strdup(server);
4049         else lc->net_conf.stun_server=NULL;
4050         if (linphone_core_ready(lc))
4051                 lp_config_set_string(lc->config,"net","stun_server",lc->net_conf.stun_server);
4052 }
4053
4054 const char * linphone_core_get_stun_server(const LinphoneCore *lc){
4055         return lc->net_conf.stun_server;
4056 }
4057
4058 const char * linphone_core_get_relay_addr(const LinphoneCore *lc){
4059         return lc->net_conf.relay;
4060 }
4061
4062 int linphone_core_set_relay_addr(LinphoneCore *lc, const char *addr){
4063         if (lc->net_conf.relay!=NULL){
4064                 ms_free(lc->net_conf.relay);
4065                 lc->net_conf.relay=NULL;
4066         }
4067         if (addr){
4068                 lc->net_conf.relay=ms_strdup(addr);
4069         }
4070         return 0;
4071 }
4072
4073 void linphone_core_set_nat_address(LinphoneCore *lc, const char *addr)
4074 {
4075         if (lc->net_conf.nat_address!=NULL){
4076                 ms_free(lc->net_conf.nat_address);
4077         }
4078         if (addr!=NULL) lc->net_conf.nat_address=ms_strdup(addr);
4079         else lc->net_conf.nat_address=NULL;
4080         if (lc->sip_conf.contact) update_primary_contact(lc);
4081 }
4082
4083 const char *linphone_core_get_nat_address(const LinphoneCore *lc) {
4084         return lc->net_conf.nat_address;
4085 }
4086
4087 const char *linphone_core_get_nat_address_resolved(LinphoneCore *lc)
4088 {
4089         struct sockaddr_storage ss;
4090         socklen_t ss_len;
4091         int error;
4092         char ipstring [INET6_ADDRSTRLEN];
4093
4094         if (lc->net_conf.nat_address==NULL) return NULL;
4095         
4096         if (parse_hostname_to_addr (lc->net_conf.nat_address, &ss, &ss_len)<0) {
4097                 return lc->net_conf.nat_address;
4098         }
4099
4100         error = getnameinfo((struct sockaddr *)&ss, ss_len,
4101                 ipstring, sizeof(ipstring), NULL, 0, NI_NUMERICHOST);
4102         if (error) {
4103                 return lc->net_conf.nat_address;
4104         }
4105
4106         if (lc->net_conf.nat_address_ip!=NULL){
4107                 ms_free(lc->net_conf.nat_address_ip);
4108         }
4109         lc->net_conf.nat_address_ip = ms_strdup (ipstring);
4110         return lc->net_conf.nat_address_ip;
4111 }
4112
4113 void linphone_core_set_firewall_policy(LinphoneCore *lc, LinphoneFirewallPolicy pol){
4114         lc->net_conf.firewall_policy=pol;
4115         if (lc->sip_conf.contact) update_primary_contact(lc);
4116         if (linphone_core_ready(lc))
4117                 lp_config_set_int(lc->config,"net","firewall_policy",pol);
4118 }
4119
4120 LinphoneFirewallPolicy linphone_core_get_firewall_policy(const LinphoneCore *lc){
4121         return lc->net_conf.firewall_policy;
4122 }
4123
4124 /**
4125  * Get the list of call logs (past calls).
4126  *
4127  * @ingroup call_logs
4128 **/
4129 const MSList * linphone_core_get_call_logs(LinphoneCore *lc){
4130         return lc->call_logs;
4131 }
4132
4133 /**
4134  * Erase the call log.
4135  *
4136  * @ingroup call_logs
4137 **/
4138 void linphone_core_clear_call_logs(LinphoneCore *lc){
4139         lc->missed_calls=0;
4140         ms_list_for_each(lc->call_logs,(void (*)(void*))linphone_call_log_destroy);
4141         lc->call_logs=ms_list_free(lc->call_logs);
4142         call_logs_write_to_config_file(lc);
4143 }
4144
4145 /**
4146  * Returns number of missed calls.
4147  * Once checked, this counter can be reset with linphone_core_reset_missed_calls_count().
4148 **/
4149 int linphone_core_get_missed_calls_count(LinphoneCore *lc) {
4150         return lc->missed_calls;
4151 }
4152
4153 /**
4154  * Resets the counter of missed calls.
4155 **/
4156 void linphone_core_reset_missed_calls_count(LinphoneCore *lc) {
4157         lc->missed_calls=0;
4158 }
4159
4160 /**
4161  * Remove a specific call log from call history list.
4162  * This function destroys the call log object. It must not be accessed anymore by the application after calling this function.
4163  * @param lc the linphone core object
4164  * @param a LinphoneCallLog object.
4165 **/
4166 void linphone_core_remove_call_log(LinphoneCore *lc, LinphoneCallLog *cl){
4167         lc->call_logs = ms_list_remove(lc->call_logs, cl);
4168         call_logs_write_to_config_file(lc);
4169         linphone_call_log_destroy(cl);
4170 }
4171
4172 static void toggle_video_preview(LinphoneCore *lc, bool_t val){
4173 #ifdef VIDEO_ENABLED
4174         if (val){
4175                 if (lc->previewstream==NULL){
4176                         lc->previewstream=video_preview_new();
4177                         video_preview_set_size(lc->previewstream,lc->video_conf.vsize);
4178                         if (lc->video_conf.displaytype)
4179                                 video_preview_set_display_filter_name(lc->previewstream,lc->video_conf.displaytype);
4180                         if (lc->preview_window_id!=0)
4181                                 video_preview_set_native_window_id(lc->previewstream,lc->preview_window_id);
4182                         video_preview_start(lc->previewstream,lc->video_conf.device);
4183                 }
4184         }else{
4185                 if (lc->previewstream!=NULL){
4186                         video_preview_stop(lc->previewstream);
4187                         lc->previewstream=NULL;
4188                 }
4189         }
4190 #endif
4191 }
4192
4193 /**
4194  * Enables video globally.
4195  *
4196  * @ingroup media_parameters
4197  * This function does not have any effect during calls. It just indicates LinphoneCore to
4198  * initiate future calls with video or not. The two boolean parameters indicate in which
4199  * direction video is enabled. Setting both to false disables video entirely.
4200  *
4201  * @param lc The LinphoneCore object
4202  * @param vcap_enabled indicates whether video capture is enabled
4203  * @param display_enabled indicates whether video display should be shown
4204  *
4205 **/
4206 void linphone_core_enable_video(LinphoneCore *lc, bool_t vcap_enabled, bool_t display_enabled){
4207 #ifndef VIDEO_ENABLED
4208         if (vcap_enabled || display_enabled)
4209                 ms_warning("This version of linphone was built without video support.");
4210 #endif
4211         lc->video_conf.capture=vcap_enabled;
4212         lc->video_conf.display=display_enabled;
4213         if (linphone_core_ready(lc)){
4214                 lp_config_set_int(lc->config,"video","display",lc->video_conf.display);
4215                 lp_config_set_int(lc->config,"video","capture",lc->video_conf.capture);
4216         }
4217         /* need to re-apply network bandwidth settings*/
4218         linphone_core_set_download_bandwidth(lc,
4219                 linphone_core_get_download_bandwidth(lc));
4220         linphone_core_set_upload_bandwidth(lc,
4221                 linphone_core_get_upload_bandwidth(lc));
4222 }
4223
4224 bool_t linphone_core_video_supported(LinphoneCore *lc){
4225 #ifdef VIDEO_ENABLED
4226         return TRUE;
4227 #else
4228         return FALSE;
4229 #endif
4230 }
4231
4232 /**
4233  * Returns TRUE if video is enabled, FALSE otherwise.
4234  * @ingroup media_parameters
4235 **/
4236 bool_t linphone_core_video_enabled(LinphoneCore *lc){
4237         return (lc->video_conf.display || lc->video_conf.capture);
4238 }
4239
4240 /**
4241  * Sets the default policy for video.
4242  * This policy defines whether:
4243  * - video shall be initiated by default for outgoing calls
4244  * - video shall be accepter by default for incoming calls
4245  * @ingroup media_parameters
4246 **/
4247 void linphone_core_set_video_policy(LinphoneCore *lc, const LinphoneVideoPolicy *policy){
4248         lc->video_policy=*policy;
4249         if (linphone_core_ready(lc)){
4250                 lp_config_set_int(lc->config,"video","automatically_initiate",policy->automatically_initiate);
4251                 lp_config_set_int(lc->config,"video","automatically_accept",policy->automatically_accept);
4252         }
4253 }
4254
4255 /**
4256  * Get the default policy for video.
4257  * See linphone_core_set_video_policy() for more details.
4258  * @ingroup media_parameters
4259 **/
4260 const LinphoneVideoPolicy *linphone_core_get_video_policy(LinphoneCore *lc){
4261         return &lc->video_policy;
4262 }
4263
4264 /**
4265  * Controls video preview enablement.
4266  *
4267  * @ingroup media_parameters
4268  * Video preview refers to the action of displaying the local webcam image
4269  * to the user while not in call.
4270 **/
4271 void linphone_core_enable_video_preview(LinphoneCore *lc, bool_t val){
4272         lc->video_conf.show_local=val;
4273         if (linphone_core_ready(lc))
4274                 lp_config_set_int(lc->config,"video","show_local",val);
4275 }
4276
4277 /**
4278  * Returns TRUE if video previewing is enabled.
4279  * @ingroup media_parameters
4280 **/
4281 bool_t linphone_core_video_preview_enabled(const LinphoneCore *lc){
4282         return lc->video_conf.show_local;
4283 }
4284
4285 /**
4286  * Enables or disable self view during calls.
4287  *
4288  * @ingroup media_parameters
4289  * Self-view refers to having local webcam image inserted in corner
4290  * of the video window during calls.
4291  * This function works at any time, including during calls.
4292 **/
4293 void linphone_core_enable_self_view(LinphoneCore *lc, bool_t val){
4294 #ifdef VIDEO_ENABLED
4295         LinphoneCall *call=linphone_core_get_current_call (lc);
4296         lc->video_conf.selfview=val;
4297         if (call && call->videostream){
4298                 video_stream_enable_self_view(call->videostream,val);
4299         }
4300         if (linphone_core_ready(lc)){
4301                 lp_config_set_int(lc->config,"video","self_view",val);
4302         }
4303 #endif
4304 }
4305
4306 /**
4307  * Returns TRUE if self-view is enabled, FALSE otherwise.
4308  *
4309  * @ingroup media_parameters
4310  *
4311  * Refer to linphone_core_enable_self_view() for details.
4312 **/
4313 bool_t linphone_core_self_view_enabled(const LinphoneCore *lc){
4314         return lc->video_conf.selfview;
4315 }
4316
4317 /**
4318  * Sets the active video device.
4319  *
4320  * @ingroup media_parameters
4321  * @param lc The LinphoneCore object
4322  * @param id the name of the video device as returned by linphone_core_get_video_devices()
4323 **/
4324 int linphone_core_set_video_device(LinphoneCore *lc, const char *id){
4325         MSWebCam *olddev=lc->video_conf.device;
4326         const char *vd;
4327         if (id!=NULL){
4328                 lc->video_conf.device=ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),id);
4329                 if (lc->video_conf.device==NULL){
4330                         ms_warning("Could not find video device %s",id);
4331                 }
4332         }
4333         if (lc->video_conf.device==NULL)
4334                 lc->video_conf.device=ms_web_cam_manager_get_default_cam(ms_web_cam_manager_get());
4335         if (olddev!=NULL && olddev!=lc->video_conf.device){
4336                 toggle_video_preview(lc,FALSE);/*restart the video local preview*/
4337         }
4338         if ( linphone_core_ready(lc) && lc->video_conf.device){
4339                 vd=ms_web_cam_get_string_id(lc->video_conf.device);
4340                 if (vd && strstr(vd,"Static picture")!=NULL){
4341                         vd=NULL;
4342                 }
4343                 lp_config_set_string(lc->config,"video","device",vd);
4344         }
4345         return 0;
4346 }
4347
4348 /**
4349  * Returns the name of the currently active video device.
4350  *
4351  * @param lc The LinphoneCore object
4352  * @ingroup media_parameters
4353 **/
4354 const char *linphone_core_get_video_device(const LinphoneCore *lc){
4355         if (lc->video_conf.device) return ms_web_cam_get_string_id(lc->video_conf.device);
4356         return NULL;
4357 }
4358
4359 #ifdef VIDEO_ENABLED
4360 static VideoStream * get_active_video_stream(LinphoneCore *lc){
4361         VideoStream *vs = NULL;
4362         LinphoneCall *call=linphone_core_get_current_call (lc);
4363         /* Select the video stream from the call in the first place */
4364         if (call && call->videostream) {
4365                 vs = call->videostream;
4366         }
4367         /* If not in call, select the video stream from the preview */
4368         if (vs == NULL && lc->previewstream) {
4369                 vs = lc->previewstream;
4370         }
4371         return vs;
4372 }
4373 #endif
4374
4375 int linphone_core_set_static_picture(LinphoneCore *lc, const char *path) {
4376 #ifdef VIDEO_ENABLED
4377         VideoStream *vs=get_active_video_stream(lc);
4378         /* If we have a video stream (either preview, either from call), we
4379                  have a source and it is using the static picture filter, then
4380                  force the filter to use that picture. */
4381         if (vs && vs->source) {
4382                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
4383                         ms_filter_call_method(vs->source, MS_STATIC_IMAGE_SET_IMAGE,
4384                                                                                                                 (void *)path);
4385                 }
4386         }
4387         /* Tell the static image filter to use that image from now on so
4388                  that the image will be used next time it has to be read */
4389         ms_static_image_set_default_image(path);
4390 #else
4391         ms_warning("Video support not compiled.");
4392 #endif
4393         return 0;
4394 }
4395
4396 const char *linphone_core_get_static_picture(LinphoneCore *lc) {
4397         const char *path=NULL;
4398 #ifdef VIDEO_ENABLED
4399         path=ms_static_image_get_default_image();       
4400 #else
4401         ms_warning("Video support not compiled.");
4402 #endif
4403         return path;
4404 }
4405
4406 int linphone_core_set_static_picture_fps(LinphoneCore *lc, float fps) {
4407 #ifdef VIDEO_ENABLED
4408         VideoStream *vs = NULL;
4409
4410         vs=get_active_video_stream(lc);
4411
4412         /* If we have a video stream (either preview, either from call), we
4413                  have a source and it is using the static picture filter, then
4414                  force the filter to use that picture. */
4415         if (vs && vs->source) {
4416                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
4417                         ms_filter_call_method(vs->source, MS_FILTER_SET_FPS,(void *)&fps);
4418                 }
4419         }
4420 #else
4421         ms_warning("Video support not compiled.");
4422 #endif
4423         return 0;
4424 }
4425
4426 float linphone_core_get_static_picture_fps(LinphoneCore *lc) {
4427 #ifdef VIDEO_ENABLED
4428         VideoStream *vs = NULL;
4429         vs=get_active_video_stream(lc);
4430         /* If we have a video stream (either preview, either from call), we
4431                  have a source and it is using the static picture filter, then
4432                  force the filter to use that picture. */
4433         if (vs && vs->source) {
4434                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
4435
4436                         float fps;
4437
4438                         ms_filter_call_method(vs->source, MS_FILTER_GET_FPS,(void *)&fps);
4439                         return fps;
4440                 }
4441         }
4442 #else
4443         ms_warning("Video support not compiled.");
4444 #endif
4445         return 0;
4446 }
4447
4448 /**
4449  * Returns the native window handle of the video window, casted as an unsigned long.
4450  *
4451  * @ingroup media_parameters
4452 **/
4453 unsigned long linphone_core_get_native_video_window_id(const LinphoneCore *lc){
4454 #ifdef VIDEO_ENABLED
4455         LinphoneCall *call=linphone_core_get_current_call (lc);
4456         if (call && call->videostream)
4457                 return video_stream_get_native_window_id(call->videostream);
4458         if (lc->previewstream)
4459                 return video_stream_get_native_window_id(lc->previewstream);
4460 #endif
4461         return lc->video_window_id;
4462 }
4463
4464 /**@ingroup media_parameters
4465  * Set the native video window id where the video is to be displayed.
4466  * If not set the core will create its own window.
4467 **/
4468 void linphone_core_set_native_video_window_id(LinphoneCore *lc, unsigned long id){
4469 #ifdef VIDEO_ENABLED
4470         LinphoneCall *call=linphone_core_get_current_call(lc);
4471         lc->video_window_id=id;
4472         if (call!=NULL && call->videostream){
4473                 video_stream_set_native_window_id(call->videostream,id);
4474         }
4475 #endif
4476 }
4477
4478 /**
4479  * Returns the native window handle of the video preview window, casted as an unsigned long.
4480  *
4481  * @ingroup media_parameters
4482 **/
4483 unsigned long linphone_core_get_native_preview_window_id(const LinphoneCore *lc){
4484 #ifdef VIDEO_ENABLED
4485         LinphoneCall *call=linphone_core_get_current_call (lc);
4486         if (call && call->videostream)
4487                 return video_stream_get_native_preview_window_id(call->videostream);
4488         if (lc->previewstream)
4489                 return video_preview_get_native_window_id(lc->previewstream);
4490 #endif
4491         return lc->preview_window_id;
4492 }
4493
4494 /**
4495  * @ingroup media_parameters
4496  * Set the native window id where the preview video (local camera) is to be displayed.
4497  * This has to be used in conjonction with linphone_core_use_preview_window().
4498  * If not set the core will create its own window.
4499 **/
4500 void linphone_core_set_native_preview_window_id(LinphoneCore *lc, unsigned long id){
4501         lc->preview_window_id=id;
4502 #ifdef VIDEO_ENABLED
4503         LinphoneCall *call=linphone_core_get_current_call(lc);
4504         if (call!=NULL && call->videostream){
4505                 video_stream_set_native_preview_window_id(call->videostream,id);
4506         }else if (lc->previewstream){
4507                 video_preview_set_native_window_id(lc->previewstream,id);
4508         }
4509 #endif
4510 }
4511
4512 /**
4513  * Can be used to disable video showing to free XV port
4514 **/
4515 void linphone_core_show_video(LinphoneCore *lc, bool_t show){
4516 #ifdef VIDEO_ENABLED
4517         ms_error("linphone_core_show_video %d", show);
4518         LinphoneCall *call=linphone_core_get_current_call(lc);
4519         if (call!=NULL && call->videostream){
4520                 video_stream_show_video(call->videostream,show);
4521         }
4522 #endif
4523 }
4524
4525 /**
4526  * Tells the core to use a separate window for local camera preview video, instead of
4527  * inserting local view within the remote video window.
4528  *
4529 **/
4530 void linphone_core_use_preview_window(LinphoneCore *lc, bool_t yesno){
4531         lc->use_preview_window=yesno;
4532 }
4533 /**
4534  * @ingroup media_parameters
4535  *returns current device orientation
4536  */
4537 int linphone_core_get_device_rotation(LinphoneCore *lc ) {
4538         return lc->device_rotation;
4539 }
4540 /**
4541  * @ingroup media_parameters
4542  * Tells the core the device current orientation. This can be used by capture filters
4543  * on mobile devices to select between portrait/landscape mode and to produce properly
4544  * oriented images. The exact meaning of the value in rotation if left to each device
4545  * specific implementations.
4546  *@param lc  object.
4547  *@param rotation . IOS supported values are 0 for UIInterfaceOrientationPortrait and 270 for UIInterfaceOrientationLandscapeRight.
4548  *
4549 **/
4550 void linphone_core_set_device_rotation(LinphoneCore *lc, int rotation) {
4551 ms_message("%s : rotation=%d\n", __FUNCTION__, rotation);
4552         lc->device_rotation = rotation;
4553 #ifdef VIDEO_ENABLED
4554         LinphoneCall *call=linphone_core_get_current_call(lc);
4555         if (call!=NULL && call->videostream){
4556                 video_stream_set_device_rotation(call->videostream,rotation);
4557         }
4558 #endif
4559 }
4560
4561 static MSVideoSizeDef supported_resolutions[]={
4562 #ifdef ENABLE_HD
4563         {       {MS_VIDEO_SIZE_1080P_W,MS_VIDEO_SIZE_1080P_H}   ,       "1080p" },
4564         {       {MS_VIDEO_SIZE_720P_W,MS_VIDEO_SIZE_720P_H}     ,       "1080p" },
4565 #endif
4566         {       {MS_VIDEO_SIZE_SVGA_W,MS_VIDEO_SIZE_SVGA_H}     ,       "svga"  },
4567         {       {MS_VIDEO_SIZE_4CIF_W,MS_VIDEO_SIZE_4CIF_H}     ,       "4cif"  },
4568         {       {MS_VIDEO_SIZE_VGA_W,MS_VIDEO_SIZE_VGA_H}       ,       "vga"   },
4569         {       {MS_VIDEO_SIZE_IOS_MEDIUM_H,MS_VIDEO_SIZE_IOS_MEDIUM_W} ,       "ios-medium"    },
4570         {       {MS_VIDEO_SIZE_CIF_W,MS_VIDEO_SIZE_CIF_H}       ,       "cif"   },
4571         {       {MS_VIDEO_SIZE_QVGA_W,MS_VIDEO_SIZE_QVGA_H}     ,       "qvga"  },
4572         {       {MS_VIDEO_SIZE_QCIF_W,MS_VIDEO_SIZE_QCIF_H}     ,       "qcif"  },      
4573         {       {0,0}                   ,       NULL    }
4574 };
4575
4576 /**
4577  * Returns the zero terminated table of supported video resolutions.
4578  *
4579  * @ingroup media_parameters
4580 **/
4581 const MSVideoSizeDef *linphone_core_get_supported_video_sizes(LinphoneCore *lc){
4582         return supported_resolutions;
4583 }
4584
4585 static MSVideoSize video_size_get_by_name(const char *name){
4586         MSVideoSizeDef *pdef=supported_resolutions;
4587         MSVideoSize null_vsize={0,0};
4588         for(;pdef->name!=NULL;pdef++){
4589                 if (strcasecmp(name,pdef->name)==0){
4590                         return pdef->vsize;
4591                 }
4592         }
4593         ms_warning("Video resolution %s is not supported in linphone.",name);
4594         return null_vsize;
4595 }
4596
4597 static const char *video_size_get_name(MSVideoSize vsize){
4598         MSVideoSizeDef *pdef=supported_resolutions;
4599         for(;pdef->name!=NULL;pdef++){
4600                 if (pdef->vsize.width==vsize.width && pdef->vsize.height==vsize.height){
4601                         return pdef->name;
4602                 }
4603         }
4604         return NULL;
4605 }
4606
4607 static bool_t video_size_supported(MSVideoSize vsize){
4608         if (video_size_get_name(vsize)) return TRUE;
4609         ms_warning("Video resolution %ix%i is not supported in linphone.",vsize.width,vsize.height);
4610         return FALSE;
4611 }
4612
4613 /**
4614  * Sets the preferred video size.
4615  *
4616  * @ingroup media_parameters
4617  * This applies only to the stream that is captured and sent to the remote party,
4618  * since we accept all standard video size on the receive path.
4619 **/
4620 void linphone_core_set_preferred_video_size(LinphoneCore *lc, MSVideoSize vsize){
4621         if (video_size_supported(vsize)){
4622                 MSVideoSize oldvsize=lc->video_conf.vsize;
4623                 lc->video_conf.vsize=vsize;
4624                 if (!ms_video_size_equal(oldvsize,vsize) && lc->previewstream!=NULL){
4625                         toggle_video_preview(lc,FALSE);
4626                         toggle_video_preview(lc,TRUE);
4627                 }
4628                 if ( linphone_core_ready(lc))
4629                         lp_config_set_string(lc->config,"video","size",video_size_get_name(vsize));
4630         }
4631 }
4632
4633 /**
4634  * Sets the preferred video size by its name.
4635  *
4636  * @ingroup media_parameters
4637  * This is identical to linphone_core_set_preferred_video_size() except
4638  * that it takes the name of the video resolution as input.
4639  * Video resolution names are: qcif, svga, cif, vga, 4cif, svga ...
4640 **/
4641 void linphone_core_set_preferred_video_size_by_name(LinphoneCore *lc, const char *name){
4642         MSVideoSize vsize=video_size_get_by_name(name);
4643         MSVideoSize default_vsize={MS_VIDEO_SIZE_CIF_W,MS_VIDEO_SIZE_CIF_H};
4644         if (vsize.width!=0)     linphone_core_set_preferred_video_size(lc,vsize);
4645         else linphone_core_set_preferred_video_size(lc,default_vsize);
4646 }
4647
4648 /**
4649  * Returns the current preferred video size for sending.
4650  *
4651  * @ingroup media_parameters
4652 **/
4653 MSVideoSize linphone_core_get_preferred_video_size(LinphoneCore *lc){
4654         return lc->video_conf.vsize;
4655 }
4656
4657 /**
4658  * Ask the core to stream audio from and to files, instead of using the soundcard.
4659 **/
4660 void linphone_core_use_files(LinphoneCore *lc, bool_t yesno){
4661         lc->use_files=yesno;
4662 }
4663
4664 /**
4665  * Sets a wav file to be played when putting somebody on hold,
4666  * or when files are used instead of soundcards (see linphone_core_use_files()).
4667  *
4668  * The file must be a 16 bit linear wav file.
4669 **/
4670 void linphone_core_set_play_file(LinphoneCore *lc, const char *file){
4671         LinphoneCall *call=linphone_core_get_current_call(lc);
4672         if (lc->play_file!=NULL){
4673                 ms_free(lc->play_file);
4674                 lc->play_file=NULL;
4675         }
4676         if (file!=NULL) {
4677                 lc->play_file=ms_strdup(file);
4678                 if (call && call->audiostream && call->audiostream->ms.ticker)
4679                         audio_stream_play(call->audiostream,file);
4680         }
4681 }
4682
4683
4684 /**
4685  * Sets a wav file where incoming stream is to be recorded,
4686  * when files are used instead of soundcards (see linphone_core_use_files()).
4687  *
4688  * This feature is different from call recording (linphone_call_params_set_record_file())
4689  * The file will be a 16 bit linear wav file.
4690 **/
4691 void linphone_core_set_record_file(LinphoneCore *lc, const char *file){
4692         LinphoneCall *call=linphone_core_get_current_call(lc);
4693         if (lc->rec_file!=NULL){
4694                 ms_free(lc->rec_file);
4695                 lc->rec_file=NULL;
4696         }
4697         if (file!=NULL) {
4698                 lc->rec_file=ms_strdup(file);
4699                 if (call && call->audiostream)
4700                         audio_stream_record(call->audiostream,file);
4701         }
4702 }
4703
4704
4705 static MSFilter *get_dtmf_gen(LinphoneCore *lc){
4706         LinphoneCall *call=linphone_core_get_current_call (lc);
4707         AudioStream *stream=NULL;
4708         if (call){
4709                 stream=call->audiostream;
4710         }else if (linphone_core_is_in_conference(lc)){
4711                 stream=lc->conf_ctx.local_participant;
4712         }
4713         if (stream){
4714                 return stream->dtmfgen;
4715         }
4716         if (lc->ringstream==NULL){
4717                 float amp=lp_config_get_float(lc->config,"sound","dtmf_player_amp",0.1);
4718                 MSSndCard *ringcard=lc->sound_conf.lsd_card ?lc->sound_conf.lsd_card : lc->sound_conf.ring_sndcard;
4719                 if (ringcard == NULL)
4720                         return NULL;
4721
4722                 lc->ringstream=ring_start(NULL,0,ringcard);
4723                 ms_filter_call_method(lc->ringstream->gendtmf,MS_DTMF_GEN_SET_DEFAULT_AMPLITUDE,&amp);
4724                 lc->dmfs_playing_start_time=time(NULL);
4725         }else{
4726                 if (lc->dmfs_playing_start_time!=0)
4727                         lc->dmfs_playing_start_time=time(NULL);
4728         }
4729         return lc->ringstream->gendtmf;
4730 }
4731
4732 /**
4733  * @ingroup media_parameters
4734  * Plays a dtmf sound to the local user.
4735  * @param lc #LinphoneCore
4736  * @param dtmf DTMF to play ['0'..'16'] | '#' | '#'
4737  * @param duration_ms duration in ms, -1 means play until next further call to #linphone_core_stop_dtmf()
4738 **/
4739 void linphone_core_play_dtmf(LinphoneCore *lc, char dtmf, int duration_ms){
4740         MSFilter *f=get_dtmf_gen(lc);
4741         if (f==NULL){
4742                 ms_error("No dtmf generator at this time !");
4743                 return;
4744         }
4745
4746         if (duration_ms>0)
4747                 ms_filter_call_method(f, MS_DTMF_GEN_PLAY, &dtmf);
4748         else ms_filter_call_method(f, MS_DTMF_GEN_START, &dtmf);
4749 }
4750
4751 /**
4752  * @ingroup media_parameters
4753  * Plays a repeated tone to the local user until next further call to #linphone_core_stop_dtmf()
4754  * @param lc #LinphoneCore
4755 **/
4756 void linphone_core_play_tone(LinphoneCore *lc){
4757         MSFilter *f=get_dtmf_gen(lc);
4758         MSDtmfGenCustomTone def;
4759         if (f==NULL){
4760                 ms_error("No dtmf generator at this time !");
4761                 return;
4762         }
4763         def.duration=300;
4764         def.frequency=500;
4765         def.amplitude=1;
4766         def.interval=2000;
4767         ms_filter_call_method(f, MS_DTMF_GEN_PLAY_CUSTOM,&def);
4768 }
4769
4770 /**
4771  * @ingroup media_parameters
4772  *
4773  * Stops playing a dtmf started by linphone_core_play_dtmf().
4774 **/
4775 void linphone_core_stop_dtmf(LinphoneCore *lc){
4776         MSFilter *f=get_dtmf_gen(lc);
4777         if (f!=NULL)
4778                 ms_filter_call_method_noarg (f, MS_DTMF_GEN_STOP);
4779 }
4780
4781
4782
4783 /**
4784  * Retrieves the user pointer that was given to linphone_core_new()
4785  *
4786  * @ingroup initializing
4787 **/
4788 void *linphone_core_get_user_data(LinphoneCore *lc){
4789         return lc->data;
4790 }
4791
4792
4793 /**
4794  * Associate a user pointer to the linphone core.
4795  *
4796  * @ingroup initializing
4797 **/
4798 void linphone_core_set_user_data(LinphoneCore *lc, void *userdata){
4799         lc->data=userdata;
4800 }
4801
4802 int linphone_core_get_mtu(const LinphoneCore *lc){
4803         return lc->net_conf.mtu;
4804 }
4805
4806 /**
4807  * Sets the maximum transmission unit size in bytes.
4808  * This information is useful for sending RTP packets.
4809  * Default value is 1500.
4810  * 
4811  * @ingroup media_parameters
4812 **/
4813 void linphone_core_set_mtu(LinphoneCore *lc, int mtu){
4814         lc->net_conf.mtu=mtu;
4815         if (mtu>0){
4816                 if (mtu<500){
4817                         ms_error("MTU too small !");
4818                         mtu=500;
4819                 }
4820                 ms_set_mtu(mtu);
4821                 ms_message("MTU is supposed to be %i, rtp payload max size will be %i",mtu, ms_get_payload_max_size());
4822         }else ms_set_mtu(0);//use mediastreamer2 default value
4823 }
4824
4825 void linphone_core_set_waiting_callback(LinphoneCore *lc, LinphoneWaitingCallback cb, void *user_context){
4826         lc->wait_cb=cb;
4827         lc->wait_ctx=user_context;
4828 }
4829
4830 void linphone_core_start_waiting(LinphoneCore *lc, const char *purpose){
4831         if (lc->wait_cb){
4832                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingStart,purpose,0);
4833         }
4834 }
4835
4836 void linphone_core_update_progress(LinphoneCore *lc, const char *purpose, float progress){
4837         if (lc->wait_cb){
4838                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingProgress,purpose,progress);
4839         }else{
4840 #ifdef WIN32
4841                 Sleep(50000);
4842 #else
4843                 usleep(50000);
4844 #endif
4845         }
4846 }
4847
4848 void linphone_core_stop_waiting(LinphoneCore *lc){
4849         if (lc->wait_cb){
4850                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingFinished,NULL,0);
4851         }
4852 }
4853
4854 void linphone_core_set_rtp_transport_factories(LinphoneCore* lc, LinphoneRtpTransportFactories *factories){
4855         lc->rtptf=factories;
4856 }
4857
4858 /**
4859  * Retrieve RTP statistics regarding current call.
4860  * @param local RTP statistics computed locally.
4861  * @param remote RTP statistics computed by far end (obtained via RTCP feedback).
4862  *
4863  * @note Remote RTP statistics is not implemented yet.
4864  *
4865  * @returns 0 or -1 if no call is running.
4866 **/
4867
4868 int linphone_core_get_current_call_stats(LinphoneCore *lc, rtp_stats_t *local, rtp_stats_t *remote){
4869         LinphoneCall *call=linphone_core_get_current_call (lc);
4870         if (call!=NULL){
4871                 if (call->audiostream!=NULL){
4872                         memset(remote,0,sizeof(*remote));
4873                         audio_stream_get_local_rtp_stats (call->audiostream,local);
4874                         return 0;
4875                 }
4876         }
4877         return -1;
4878 }
4879
4880 void net_config_uninit(LinphoneCore *lc)
4881 {
4882         net_config_t *config=&lc->net_conf;
4883
4884         if (config->stun_server!=NULL){
4885                 ms_free(lc->net_conf.stun_server);
4886         }
4887         if (config->nat_address!=NULL){
4888                 lp_config_set_string(lc->config,"net","nat_address",config->nat_address);
4889                 ms_free(lc->net_conf.nat_address);
4890         }
4891         if (lc->net_conf.nat_address_ip !=NULL){
4892                 ms_free(lc->net_conf.nat_address_ip);
4893         }
4894         lp_config_set_int(lc->config,"net","mtu",config->mtu);
4895 }
4896
4897
4898 void sip_config_uninit(LinphoneCore *lc)
4899 {
4900         MSList *elem;
4901         int i;
4902         sip_config_t *config=&lc->sip_conf;
4903         
4904         lp_config_set_int(lc->config,"sip","guess_hostname",config->guess_hostname);
4905         lp_config_set_string(lc->config,"sip","contact",config->contact);
4906         lp_config_set_int(lc->config,"sip","inc_timeout",config->inc_timeout);
4907         lp_config_set_int(lc->config,"sip","in_call_timeout",config->in_call_timeout);
4908         lp_config_set_int(lc->config,"sip","use_info",config->use_info);
4909         lp_config_set_int(lc->config,"sip","use_rfc2833",config->use_rfc2833);
4910         lp_config_set_int(lc->config,"sip","use_ipv6",config->ipv6_enabled);
4911         lp_config_set_int(lc->config,"sip","register_only_when_network_is_up",config->register_only_when_network_is_up);
4912
4913
4914         
4915
4916         for(elem=config->proxies,i=0;elem!=NULL;elem=ms_list_next(elem),i++){
4917                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)(elem->data);
4918                 linphone_proxy_config_edit(cfg);        /* to unregister */
4919         }
4920
4921         for (i=0;i<20;i++){
4922                 sal_iterate(lc->sal);
4923 #ifndef WIN32
4924                 usleep(100000);
4925 #else
4926                 Sleep(100);
4927 #endif
4928         }
4929
4930         ms_list_for_each(config->proxies,(void (*)(void*)) linphone_proxy_config_destroy);
4931         ms_list_free(config->proxies);
4932         config->proxies=NULL;
4933
4934         linphone_proxy_config_write_to_config_file(lc->config,NULL,i);  /*mark the end */
4935
4936         ms_list_for_each(lc->auth_info,(void (*)(void*))linphone_auth_info_destroy);
4937         ms_list_free(lc->auth_info);
4938         lc->auth_info=NULL;
4939
4940         sal_uninit(lc->sal);
4941         lc->sal=NULL;
4942
4943         if (lc->sip_conf.guessed_contact)
4944                 ms_free(lc->sip_conf.guessed_contact);
4945         if (config->contact)
4946                 ms_free(config->contact);
4947
4948 }
4949
4950 void rtp_config_uninit(LinphoneCore *lc)
4951 {
4952         rtp_config_t *config=&lc->rtp_conf;
4953         if (config->audio_rtp_min_port == config->audio_rtp_max_port) {
4954                 lp_config_set_int(lc->config, "rtp", "audio_rtp_port", config->audio_rtp_min_port);
4955         } else {
4956                 lp_config_set_range(lc->config, "rtp", "audio_rtp_port", config->audio_rtp_min_port, config->audio_rtp_max_port);
4957         }
4958         if (config->video_rtp_min_port == config->video_rtp_max_port) {
4959                 lp_config_set_int(lc->config, "rtp", "video_rtp_port", config->video_rtp_min_port);
4960         } else {
4961                 lp_config_set_range(lc->config, "rtp", "video_rtp_port", config->video_rtp_min_port, config->video_rtp_max_port);
4962         }
4963         lp_config_set_int(lc->config,"rtp","audio_jitt_comp",config->audio_jitt_comp);
4964         lp_config_set_int(lc->config,"rtp","video_jitt_comp",config->video_jitt_comp);
4965         lp_config_set_int(lc->config,"rtp","nortp_timeout",config->nortp_timeout);
4966         lp_config_set_int(lc->config,"rtp","audio_adaptive_jitt_comp_enabled",config->audio_adaptive_jitt_comp_enabled);
4967         lp_config_set_int(lc->config,"rtp","video_adaptive_jitt_comp_enabled",config->video_adaptive_jitt_comp_enabled);
4968 }
4969
4970 static void sound_config_uninit(LinphoneCore *lc)
4971 {
4972         sound_config_t *config=&lc->sound_conf;
4973         ms_free(config->cards);
4974
4975         lp_config_set_string(lc->config,"sound","remote_ring",config->remote_ring);
4976         lp_config_set_float(lc->config,"sound","playback_gain_db",config->soft_play_lev);
4977         lp_config_set_float(lc->config,"sound","mic_gain_db",config->soft_mic_lev);
4978
4979         if (config->local_ring) ms_free(config->local_ring);
4980         if (config->remote_ring) ms_free(config->remote_ring);
4981         ms_snd_card_manager_destroy();
4982 }
4983
4984 static void video_config_uninit(LinphoneCore *lc)
4985 {
4986         lp_config_set_string(lc->config,"video","size",video_size_get_name(linphone_core_get_preferred_video_size(lc)));
4987         lp_config_set_int(lc->config,"video","display",lc->video_conf.display);
4988         lp_config_set_int(lc->config,"video","capture",lc->video_conf.capture);
4989         if (lc->video_conf.cams)
4990                 ms_free(lc->video_conf.cams);
4991 }
4992
4993 void _linphone_core_codec_config_write(LinphoneCore *lc){
4994         if (linphone_core_ready(lc)){
4995                 PayloadType *pt;
4996                 codecs_config_t *config=&lc->codecs_conf;
4997                 MSList *node;
4998                 char key[50];
4999                 int index;
5000                 index=0;
5001                 for(node=config->audio_codecs;node!=NULL;node=ms_list_next(node)){
5002                         pt=(PayloadType*)(node->data);
5003                         sprintf(key,"audio_codec_%i",index);
5004                         lp_config_set_string(lc->config,key,"mime",pt->mime_type);
5005                         lp_config_set_int(lc->config,key,"rate",pt->clock_rate);
5006                         lp_config_set_int(lc->config,key,"channels",pt->channels);
5007                         lp_config_set_int(lc->config,key,"enabled",linphone_core_payload_type_enabled(lc,pt));
5008                         index++;
5009                 }
5010                 sprintf(key,"audio_codec_%i",index);
5011                 lp_config_clean_section (lc->config,key);
5012
5013                 index=0;
5014                 for(node=config->video_codecs;node!=NULL;node=ms_list_next(node)){
5015                         pt=(PayloadType*)(node->data);
5016                         sprintf(key,"video_codec_%i",index);
5017                         lp_config_set_string(lc->config,key,"mime",pt->mime_type);
5018                         lp_config_set_int(lc->config,key,"rate",pt->clock_rate);
5019                         lp_config_set_int(lc->config,key,"enabled",linphone_core_payload_type_enabled(lc,pt));
5020                         lp_config_set_string(lc->config,key,"recv_fmtp",pt->recv_fmtp);
5021                         index++;
5022                 }
5023                 sprintf(key,"video_codec_%i",index);
5024                 lp_config_clean_section (lc->config,key);
5025         }
5026 }
5027
5028 static void codecs_config_uninit(LinphoneCore *lc)
5029 {
5030         _linphone_core_codec_config_write(lc);
5031         ms_list_free(lc->codecs_conf.audio_codecs);
5032         ms_list_free(lc->codecs_conf.video_codecs);
5033 }
5034
5035 void ui_config_uninit(LinphoneCore* lc)
5036 {
5037         if (lc->friends){
5038                 ms_list_for_each(lc->friends,(void (*)(void *))linphone_friend_destroy);
5039                 ms_list_free(lc->friends);
5040                 lc->friends=NULL;
5041         }
5042 }
5043
5044 /**
5045  * Returns the LpConfig object used to manage the storage (config) file.
5046  *
5047  * @ingroup misc
5048  * The application can use the LpConfig object to insert its own private
5049  * sections and pairs of key=value in the configuration file.
5050  *
5051 **/
5052 LpConfig *linphone_core_get_config(LinphoneCore *lc){
5053         return lc->config;
5054 }
5055
5056 static void linphone_core_uninit(LinphoneCore *lc)
5057 {
5058         linphone_core_free_hooks(lc);
5059         while(lc->calls)
5060         {
5061                 LinphoneCall *the_call = lc->calls->data;
5062                 linphone_core_terminate_call(lc,the_call);
5063                 linphone_core_iterate(lc);
5064 #ifdef WIN32
5065                 Sleep(50000);
5066 #else
5067                 usleep(50000);
5068 #endif
5069         }
5070
5071 #ifdef BUILD_UPNP
5072         linphone_upnp_context_destroy(lc->upnp);
5073         lc->upnp = NULL;
5074 #endif  //BUILD_UPNP
5075
5076         if (lc->friends)
5077                 ms_list_for_each(lc->friends,(void (*)(void *))linphone_friend_close_subscriptions);
5078         linphone_core_set_state(lc,LinphoneGlobalShutdown,"Shutting down");
5079 #ifdef VIDEO_ENABLED
5080         if (lc->previewstream!=NULL){
5081                 video_preview_stop(lc->previewstream);
5082                 lc->previewstream=NULL;
5083         }
5084 #endif
5085         ms_event_queue_destroy(lc->msevq);
5086         lc->msevq=NULL;
5087         /* save all config */
5088         net_config_uninit(lc);
5089         rtp_config_uninit(lc);
5090         if (lc->ringstream) ring_stop(lc->ringstream);
5091         sound_config_uninit(lc);
5092         video_config_uninit(lc);
5093         codecs_config_uninit(lc);
5094         ui_config_uninit(lc);
5095         sip_config_uninit(lc);
5096         if (lp_config_needs_commit(lc->config)) lp_config_sync(lc->config);
5097         lp_config_destroy(lc->config);
5098         lc->config = NULL; /* Mark the config as NULL to block further calls */
5099         sip_setup_unregister_all();
5100
5101         ms_list_for_each(lc->call_logs,(void (*)(void*))linphone_call_log_destroy);
5102         lc->call_logs=ms_list_free(lc->call_logs);
5103         
5104         ms_list_for_each(lc->last_recv_msg_ids,ms_free);
5105         lc->last_recv_msg_ids=ms_list_free(lc->last_recv_msg_ids);
5106
5107         linphone_core_free_payload_types(lc);
5108         ortp_exit();
5109         linphone_core_set_state(lc,LinphoneGlobalOff,"Off");
5110 #ifdef TUNNEL_ENABLED
5111         if (lc->tunnel) linphone_tunnel_destroy(lc->tunnel);
5112 #endif
5113 }
5114
5115 static void set_network_reachable(LinphoneCore* lc,bool_t isReachable, time_t curtime){
5116         ms_message("Network state is now [%s]",isReachable?"UP":"DOWN");
5117         // second get the list of available proxies
5118         const MSList *elem=linphone_core_get_proxy_config_list(lc);
5119         for(;elem!=NULL;elem=elem->next){
5120                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
5121                 if (linphone_proxy_config_register_enabled(cfg) ) {
5122                         if (!isReachable) {
5123                                 linphone_proxy_config_set_state(cfg, LinphoneRegistrationNone,"Registration impossible (network down)");
5124                         }else{
5125                                 cfg->commit=TRUE;
5126                         }
5127                 }
5128         }
5129         lc->netup_time=curtime;
5130         lc->network_reachable=isReachable;
5131         if(!isReachable) {
5132                 sal_reset_transports(lc->sal);
5133         }
5134 }
5135
5136 void linphone_core_refresh_registers(LinphoneCore* lc) {
5137         const MSList *elem;
5138         if (!lc->network_reachable) {
5139                 ms_warning("Refresh register operation not available (network unreachable)");
5140                 return;
5141         }
5142         elem=linphone_core_get_proxy_config_list(lc);
5143         for(;elem!=NULL;elem=elem->next){
5144                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
5145                 if (linphone_proxy_config_register_enabled(cfg) && linphone_proxy_config_get_expires(cfg)>0) {
5146                         linphone_proxy_config_refresh_register(cfg);
5147                 }
5148         }
5149 }
5150
5151 void __linphone_core_invalidate_registers(LinphoneCore* lc){
5152         const MSList *elem=linphone_core_get_proxy_config_list(lc);
5153         for(;elem!=NULL;elem=elem->next){
5154                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
5155                 if (linphone_proxy_config_register_enabled(cfg)) {
5156                         linphone_proxy_config_edit(cfg);
5157                         linphone_proxy_config_done(cfg);
5158                 }
5159         }
5160 }
5161
5162 void linphone_core_set_network_reachable(LinphoneCore* lc,bool_t isReachable) {
5163         //first disable automatic mode
5164         if (lc->auto_net_state_mon) {
5165                 ms_message("Disabling automatic network state monitoring");
5166                 lc->auto_net_state_mon=FALSE;
5167         }
5168         set_network_reachable(lc,isReachable, ms_time(NULL));
5169 }
5170
5171 bool_t linphone_core_is_network_reachable(LinphoneCore* lc) {
5172         return lc->network_reachable;
5173 }
5174 ortp_socket_t linphone_core_get_sip_socket(LinphoneCore *lc){
5175         return sal_get_socket(lc->sal);
5176 }
5177 /**
5178  * Destroys a LinphoneCore
5179  *
5180  * @ingroup initializing
5181 **/
5182 void linphone_core_destroy(LinphoneCore *lc){
5183         linphone_core_uninit(lc);
5184         ms_free(lc);
5185 }
5186 /**
5187  * Get the number of Call
5188  *
5189  * @ingroup call_control
5190 **/
5191 int linphone_core_get_calls_nb(const LinphoneCore *lc){
5192         return  ms_list_size(lc->calls);;
5193 }
5194
5195 /**
5196  * Check if we do not have exceed the number of simultaneous call
5197  *
5198  * @ingroup call_control
5199 **/
5200 bool_t linphone_core_can_we_add_call(LinphoneCore *lc)
5201 {
5202         if(linphone_core_get_calls_nb(lc) < lc->max_calls)
5203                 return TRUE;
5204         ms_message("Maximum amount of simultaneous calls reached !");
5205         return FALSE;
5206 }
5207
5208
5209 int linphone_core_add_call( LinphoneCore *lc, LinphoneCall *call)
5210 {
5211         if(linphone_core_can_we_add_call(lc))
5212         {
5213                 lc->calls = ms_list_append(lc->calls,call);
5214                 return 0;
5215         }
5216         return -1;
5217 }
5218
5219 int linphone_core_del_call( LinphoneCore *lc, LinphoneCall *call)
5220 {
5221         MSList *it;
5222         MSList *the_calls = lc->calls;
5223
5224         it=ms_list_find(the_calls,call);
5225         if (it)
5226         {
5227                 the_calls = ms_list_remove_link(the_calls,it);
5228         }
5229         else
5230         {
5231                 ms_warning("could not find the call into the list\n");
5232                 return -1;
5233         }
5234         lc->calls = the_calls;
5235         return 0;
5236 }
5237
5238 /**
5239  * Specifiies a ring back tone to be played to far end during incoming calls.
5240 **/
5241 void linphone_core_set_remote_ringback_tone(LinphoneCore *lc, const char *file){
5242         if (lc->sound_conf.ringback_tone){
5243                 ms_free(lc->sound_conf.ringback_tone);
5244                 lc->sound_conf.ringback_tone=NULL;
5245         }
5246         if (file)
5247                 lc->sound_conf.ringback_tone=ms_strdup(file);
5248 }
5249
5250 /**
5251  * Returns the ring back tone played to far end during incoming calls.
5252 **/
5253 const char *linphone_core_get_remote_ringback_tone(const LinphoneCore *lc){
5254         return lc->sound_conf.ringback_tone;
5255 }
5256
5257 static PayloadType* find_payload_type_from_list(const char* type, int rate, int channels, const MSList* from) {
5258         const MSList *elem;
5259         for(elem=from;elem!=NULL;elem=elem->next){
5260                 PayloadType *pt=(PayloadType*)elem->data;
5261                 if ((strcasecmp((char*)type, payload_type_get_mime(pt)) == 0)
5262                         && (rate == LINPHONE_FIND_PAYLOAD_IGNORE_RATE || rate==pt->clock_rate)
5263                         && (channels == LINPHONE_FIND_PAYLOAD_IGNORE_CHANNELS || channels==pt->channels)) {
5264                         return pt;
5265                 }
5266         }
5267         return NULL;
5268 }
5269
5270
5271 PayloadType* linphone_core_find_payload_type(LinphoneCore* lc, const char* type, int rate, int channels) {
5272         PayloadType* result = find_payload_type_from_list(type, rate, channels, linphone_core_get_audio_codecs(lc));
5273         if (result)  {
5274                 return result;
5275         } else {
5276                 result = find_payload_type_from_list(type, rate, 0, linphone_core_get_video_codecs(lc));
5277                 if (result) {
5278                         return result;
5279                 }
5280         }
5281         /*not found*/
5282         return NULL;
5283 }
5284
5285 const char *linphone_global_state_to_string(LinphoneGlobalState gs){
5286         switch(gs){
5287                 case LinphoneGlobalOff:
5288                         return "LinphoneGlobalOff";
5289                 break;
5290                 case LinphoneGlobalOn:
5291                         return "LinphoneGlobalOn";
5292                 break;
5293                 case LinphoneGlobalStartup:
5294                         return "LinphoneGlobalStartup";
5295                 break;
5296                 case LinphoneGlobalShutdown:
5297                         return "LinphoneGlobalShutdown";
5298                 break;
5299         }
5300         return NULL;
5301 }
5302
5303 LinphoneGlobalState linphone_core_get_global_state(const LinphoneCore *lc){
5304         return lc->state;
5305 }
5306
5307 LinphoneCallParams *linphone_core_create_default_call_parameters(LinphoneCore *lc){
5308         LinphoneCallParams *p=ms_new0(LinphoneCallParams,1);
5309         linphone_core_init_default_params(lc, p);
5310         return p;
5311 }
5312
5313 const char *linphone_reason_to_string(LinphoneReason err){
5314         switch(err){
5315                 case LinphoneReasonNone:
5316                         return "No error";
5317                 case LinphoneReasonNoResponse:
5318                         return "No response";
5319                 case LinphoneReasonBadCredentials:
5320                         return "Bad credentials";
5321                 case LinphoneReasonDeclined:
5322                         return "Call declined";
5323                 case LinphoneReasonNotFound:
5324                         return "User not found";
5325                 case LinphoneReasonNotAnswered:
5326                         return "Not answered";
5327                 case LinphoneReasonBusy:
5328                         return "Busy";
5329         }
5330         return "unknown error";
5331 }
5332
5333 const char *linphone_error_to_string(LinphoneReason err){
5334         return linphone_reason_to_string(err);
5335 }
5336 /**
5337  * Enables signaling keep alive
5338  */
5339 void linphone_core_enable_keep_alive(LinphoneCore* lc,bool_t enable) {
5340         if (enable > 0) {
5341                 sal_use_tcp_tls_keepalive(lc->sal,lc->sip_conf.tcp_tls_keepalive);
5342                 sal_set_keepalive_period(lc->sal,lc->sip_conf.keepalive_period);
5343         } else {
5344                 sal_set_keepalive_period(lc->sal,0);
5345         }
5346 }
5347 /**
5348  * Is signaling keep alive enabled
5349  */
5350 bool_t linphone_core_keep_alive_enabled(LinphoneCore* lc) {
5351         return sal_get_keepalive_period(lc->sal) > 0;
5352 }
5353
5354 void linphone_core_start_dtmf_stream(LinphoneCore* lc) {
5355         get_dtmf_gen(lc); /*make sure ring stream is started*/
5356         lc->ringstream_autorelease=FALSE; /*disable autorelease mode*/
5357 }
5358
5359 void linphone_core_stop_dtmf_stream(LinphoneCore* lc) {
5360         if (lc->ringstream && lc->dmfs_playing_start_time!=0) {
5361                 ring_stop(lc->ringstream);
5362                 lc->ringstream=NULL;
5363         }
5364 }
5365
5366 int linphone_core_get_max_calls(LinphoneCore *lc) {
5367         return lc->max_calls;
5368 }
5369 void linphone_core_set_max_calls(LinphoneCore *lc, int max) {
5370         lc->max_calls=max;
5371 }
5372
5373 typedef struct Hook{
5374         LinphoneCoreIterateHook fun;
5375         void *data;
5376 }Hook;
5377
5378 static Hook *hook_new(LinphoneCoreIterateHook hook, void *hook_data){
5379         Hook *h=ms_new(Hook,1);
5380         h->fun=hook;
5381         h->data=hook_data;
5382         return h;
5383 }
5384
5385 static void hook_invoke(Hook *h){
5386         h->fun(h->data);
5387 }
5388
5389 void linphone_core_add_iterate_hook(LinphoneCore *lc, LinphoneCoreIterateHook hook, void *hook_data){
5390         lc->hooks=ms_list_append(lc->hooks,hook_new(hook,hook_data));
5391 }
5392
5393 static void linphone_core_run_hooks(LinphoneCore *lc){
5394         ms_list_for_each(lc->hooks,(void (*)(void*))hook_invoke);
5395 }
5396
5397 static void linphone_core_free_hooks(LinphoneCore *lc){
5398         ms_list_for_each(lc->hooks,(void (*)(void*))ms_free);
5399         ms_list_free(lc->hooks);
5400         lc->hooks=NULL;
5401 }
5402
5403 void linphone_core_remove_iterate_hook(LinphoneCore *lc, LinphoneCoreIterateHook hook, void *hook_data){
5404         MSList *elem;
5405         for(elem=lc->hooks;elem!=NULL;elem=elem->next){
5406                 Hook *h=(Hook*)elem->data;
5407                 if (h->fun==hook && h->data==hook_data){
5408                         ms_list_remove_link(lc->hooks,elem);
5409                         ms_free(h);
5410                         return;
5411                 }
5412         }
5413         ms_error("linphone_core_remove_iterate_hook(): No such hook found.");
5414 }
5415
5416 void linphone_core_set_zrtp_secrets_file(LinphoneCore *lc, const char* file){
5417         if (lc->zrtp_secrets_cache != NULL) {
5418                 ms_free(lc->zrtp_secrets_cache);
5419         }
5420         lc->zrtp_secrets_cache=file ? ms_strdup(file) : NULL;
5421 }
5422
5423 const char *linphone_core_get_zrtp_secrets_file(LinphoneCore *lc){
5424         return lc->zrtp_secrets_cache;
5425 }
5426
5427 const LinphoneCall* linphone_core_find_call_from_uri(LinphoneCore *lc, const char *uri) {
5428         if (uri == NULL) return NULL;
5429         MSList *calls=lc->calls;
5430         while(calls) {
5431                 const LinphoneCall *c=(LinphoneCall*)calls->data;
5432                 calls=calls->next;
5433                 const LinphoneAddress *address = linphone_call_get_remote_address(c);
5434                 char *current_uri=linphone_address_as_string_uri_only(address);
5435                 if (strcmp(uri,current_uri)==0) {
5436                         ms_free(current_uri);
5437                         return c;
5438                 } else {
5439                         ms_free(current_uri);
5440                 }
5441         }
5442         return NULL;
5443 }
5444
5445
5446 /**
5447  * Check if a call will need the sound resources.
5448  *
5449  * @ingroup call_control
5450  * @param lc The LinphoneCore
5451 **/
5452 bool_t linphone_core_sound_resources_locked(LinphoneCore *lc){
5453         MSList *calls=lc->calls;
5454         while(calls) {
5455                 LinphoneCall *c=(LinphoneCall*)calls->data;
5456                 calls=calls->next;
5457                 switch (c->state) {
5458                         case LinphoneCallOutgoingInit:
5459                         case LinphoneCallOutgoingProgress:
5460                         case LinphoneCallOutgoingRinging:
5461                         case LinphoneCallOutgoingEarlyMedia:
5462                         case LinphoneCallConnected:
5463                         case LinphoneCallRefered:
5464                         case LinphoneCallIncomingEarlyMedia:
5465                         case LinphoneCallUpdating:
5466                                 return TRUE;
5467                         default:
5468                                 break;
5469                 }
5470         }
5471         return FALSE;
5472 }
5473
5474 void linphone_core_set_srtp_enabled(LinphoneCore *lc, bool_t enabled) {
5475         lp_config_set_int(lc->config,"sip","srtp",(int)enabled);
5476 }
5477
5478 /**
5479  * Returns whether a media encryption scheme is supported by the LinphoneCore engine
5480 **/
5481 bool_t linphone_core_media_encryption_supported(const LinphoneCore *lc, LinphoneMediaEncryption menc){
5482         switch(menc){
5483                 case LinphoneMediaEncryptionSRTP:
5484                         return ortp_srtp_supported();
5485                 case LinphoneMediaEncryptionZRTP:
5486                         return ortp_zrtp_available();
5487                 case LinphoneMediaEncryptionNone:
5488                         return TRUE;
5489         }
5490         return FALSE;
5491 }
5492
5493 int linphone_core_set_media_encryption(LinphoneCore *lc, enum LinphoneMediaEncryption menc) {
5494         const char *type="none";
5495         int ret=0;
5496         if (menc == LinphoneMediaEncryptionSRTP){
5497                 if (!ortp_srtp_supported()){
5498                         ms_warning("SRTP not supported by library.");
5499                         type="none";
5500                         ret=-1;
5501                 }else type="srtp";
5502         }else if (menc == LinphoneMediaEncryptionZRTP){
5503                 if (!ortp_zrtp_available()){
5504                         ms_warning("ZRTP not supported by library.");
5505                         type="none";
5506                         ret=-1;
5507                 }else type="zrtp";
5508         }
5509         lp_config_set_string(lc->config,"sip","media_encryption",type);
5510         return ret;
5511 }
5512
5513 LinphoneMediaEncryption linphone_core_get_media_encryption(LinphoneCore *lc) {
5514         const char* menc = lp_config_get_string(lc->config, "sip", "media_encryption", NULL);
5515         
5516         if (menc == NULL)
5517                 return LinphoneMediaEncryptionNone;
5518         else if (strcmp(menc, "srtp")==0)
5519                 return LinphoneMediaEncryptionSRTP;
5520         else if (strcmp(menc, "zrtp")==0)
5521                 return LinphoneMediaEncryptionZRTP;
5522         else
5523                 return LinphoneMediaEncryptionNone;
5524 }
5525
5526 bool_t linphone_core_is_media_encryption_mandatory(LinphoneCore *lc) {
5527         return (bool_t)lp_config_get_int(lc->config, "sip", "media_encryption_mandatory", 0);
5528 }
5529
5530 void linphone_core_set_media_encryption_mandatory(LinphoneCore *lc, bool_t m) {
5531         lp_config_set_int(lc->config, "sip", "media_encryption_mandatory", (int)m);
5532 }
5533
5534 void linphone_core_init_default_params(LinphoneCore*lc, LinphoneCallParams *params) {
5535         params->has_video=linphone_core_video_enabled(lc) && lc->video_policy.automatically_initiate;
5536         params->media_encryption=linphone_core_get_media_encryption(lc);
5537         params->in_conference=FALSE;
5538 }
5539
5540 void linphone_core_set_device_identifier(LinphoneCore *lc,const char* device_id) {
5541         if (lc->device_id) ms_free(lc->device_id);
5542         lc->device_id=ms_strdup(device_id);
5543 }
5544 const char*  linphone_core_get_device_identifier(const LinphoneCore *lc) {
5545         return lc->device_id;
5546 }
5547
5548 /**
5549  * Set the DSCP field for SIP signaling channel.
5550  * 
5551  * @ingroup network_parameters
5552  * * The DSCP defines the quality of service in IP packets.
5553  * 
5554 **/
5555 void linphone_core_set_sip_dscp(LinphoneCore *lc, int dscp){
5556         sal_set_dscp(lc->sal,dscp);
5557         if (linphone_core_ready(lc)){
5558                 lp_config_set_int_hex(lc->config,"sip","dscp",dscp);
5559                 apply_transports(lc);
5560         }
5561 }
5562
5563 /**
5564  * Get the DSCP field for SIP signaling channel.
5565  * 
5566  * @ingroup network_parameters
5567  * * The DSCP defines the quality of service in IP packets.
5568  * 
5569 **/
5570 int linphone_core_get_sip_dscp(const LinphoneCore *lc){
5571         return lp_config_get_int(lc->config,"sip","dscp",0x1a);
5572 }
5573
5574 /**
5575  * Set the DSCP field for outgoing audio streams.
5576  *
5577  * @ingroup network_parameters
5578  * The DSCP defines the quality of service in IP packets.
5579  * 
5580 **/
5581 void linphone_core_set_audio_dscp(LinphoneCore *lc, int dscp){
5582         if (linphone_core_ready(lc))
5583                 lp_config_set_int_hex(lc->config,"rtp","audio_dscp",dscp);
5584 }
5585
5586 /**
5587  * Get the DSCP field for outgoing audio streams.
5588  *
5589  * @ingroup network_parameters
5590  * The DSCP defines the quality of service in IP packets.
5591  * 
5592 **/
5593 int linphone_core_get_audio_dscp(const LinphoneCore *lc){
5594         return lp_config_get_int(lc->config,"rtp","audio_dscp",0x2e);
5595 }
5596
5597 /**
5598  * Set the DSCP field for outgoing video streams.
5599  *
5600  * @ingroup network_parameters
5601  * The DSCP defines the quality of service in IP packets.
5602  * 
5603 **/
5604 void linphone_core_set_video_dscp(LinphoneCore *lc, int dscp){
5605         if (linphone_core_ready(lc))
5606                 lp_config_set_int_hex(lc->config,"rtp","video_dscp",dscp);
5607         
5608 }
5609
5610 /**
5611  * Get the DSCP field for outgoing video streams.
5612  *
5613  * @ingroup network_parameters
5614  * The DSCP defines the quality of service in IP packets.
5615  * 
5616 **/
5617 int linphone_core_get_video_dscp(const LinphoneCore *lc){
5618         return lp_config_get_int(lc->config,"rtp","video_dscp",0x2e);
5619 }