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