]> sjero.net Git - linphone/blob - coreapi/linphonecore.c
add use_101 option to disable 101 dialog established
[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 #include "linphonecore.h"
21 #include "sipsetup.h"
22 #include "lpconfig.h"
23 #include "private.h"
24
25 #include <ortp/telephonyevents.h>
26 #include "mediastreamer2/mediastream.h"
27 #include "mediastreamer2/mseventqueue.h"
28 #include "mediastreamer2/msvolume.h"
29 #include "mediastreamer2/msequalizer.h"
30 #include "mediastreamer2/dtmfgen.h"
31
32 #ifdef INET6
33 #ifndef WIN32
34 #include <netdb.h>
35 #endif
36 #endif
37
38 /*#define UNSTANDART_GSM_11K 1*/
39
40 static const char *liblinphone_version=LIBLINPHONE_VERSION;
41 static void set_network_reachable(LinphoneCore* lc,bool_t isReachable, time_t curtime);
42 static void linphone_core_run_hooks(LinphoneCore *lc);
43 static void linphone_core_free_hooks(LinphoneCore *lc);
44
45 #include "enum.h"
46 const char *linphone_core_get_nat_address_resolved(LinphoneCore *lc);
47 void linphone_core_get_local_ip(LinphoneCore *lc, const char *dest, char *result);
48 static void toggle_video_preview(LinphoneCore *lc, bool_t val);
49
50 /* relative path where is stored local ring*/
51 #define LOCAL_RING "rings/oldphone.wav"
52 /* same for remote ring (ringback)*/
53 #define REMOTE_RING "ringback.wav"
54 #define HOLD_MUSIC "rings/toy-mono.wav"
55
56
57 extern SalCallbacks linphone_sal_callbacks;
58
59 void lc_callback_obj_init(LCCallbackObj *obj,LinphoneCoreCbFunc func,void* ud)
60 {
61   obj->_func=func;
62   obj->_user_data=ud;
63 }
64
65 int lc_callback_obj_invoke(LCCallbackObj *obj, LinphoneCore *lc){
66         if (obj->_func!=NULL) obj->_func(lc,obj->_user_data);
67         return 0;
68 }
69
70                 
71 /*prevent a gcc bug with %c*/
72 static size_t my_strftime(char *s, size_t max, const char  *fmt,  const struct tm *tm){
73 #if !defined(_WIN32_WCE)
74         return strftime(s, max, fmt, tm);
75 #else
76         return 0;
77         /*FIXME*/
78 #endif /*_WIN32_WCE*/
79 }
80
81 static void set_call_log_date(LinphoneCallLog *cl, const struct tm *loctime){
82         my_strftime(cl->start_date,sizeof(cl->start_date),"%c",loctime);
83 }
84
85 LinphoneCallLog * linphone_call_log_new(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
86         LinphoneCallLog *cl=ms_new0(LinphoneCallLog,1);
87         struct tm loctime;
88         cl->dir=call->dir;
89 #ifdef WIN32
90 #if !defined(_WIN32_WCE)
91         loctime=*localtime(&call->start_time);
92         /*FIXME*/
93 #endif /*_WIN32_WCE*/
94 #else
95         localtime_r(&call->start_time,&loctime);
96 #endif
97         set_call_log_date(cl,&loctime);
98         cl->from=from;
99         cl->to=to;
100     cl->status=LinphoneCallAborted; /*default status*/
101         return cl;
102 }
103
104 void call_logs_write_to_config_file(LinphoneCore *lc){
105         MSList *elem;
106         char logsection[32];
107         int i;
108         char *tmp;
109         LpConfig *cfg=lc->config;
110
111         if (linphone_core_get_global_state (lc)==LinphoneGlobalStartup) return;
112         
113         for(i=0,elem=lc->call_logs;elem!=NULL;elem=elem->next,++i){
114                 LinphoneCallLog *cl=(LinphoneCallLog*)elem->data;
115                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
116                 lp_config_set_int(cfg,logsection,"dir",cl->dir);
117                 lp_config_set_int(cfg,logsection,"status",cl->status);
118                 tmp=linphone_address_as_string(cl->from);
119                 lp_config_set_string(cfg,logsection,"from",tmp);
120                 ms_free(tmp);
121                 tmp=linphone_address_as_string(cl->to);
122                 lp_config_set_string(cfg,logsection,"to",tmp);
123                 ms_free(tmp);
124                 lp_config_set_string(cfg,logsection,"start_date",cl->start_date);
125                 lp_config_set_int(cfg,logsection,"duration",cl->duration);
126                 if (cl->refkey) lp_config_set_string(cfg,logsection,"refkey",cl->refkey);
127         }
128         for(;i<lc->max_call_logs;++i){
129                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
130                 lp_config_clean_section(cfg,logsection);
131         }
132 }
133
134 static void call_logs_read_from_config_file(LinphoneCore *lc){
135         char logsection[32];
136         int i;
137         const char *tmp;
138         LpConfig *cfg=lc->config;
139         for(i=0;;++i){
140                 snprintf(logsection,sizeof(logsection),"call_log_%i",i);
141                 if (lp_config_has_section(cfg,logsection)){
142                         LinphoneCallLog *cl=ms_new0(LinphoneCallLog,1);
143                         cl->dir=lp_config_get_int(cfg,logsection,"dir",0);
144                         cl->status=lp_config_get_int(cfg,logsection,"status",0);
145                         tmp=lp_config_get_string(cfg,logsection,"from",NULL);
146                         if (tmp) cl->from=linphone_address_new(tmp);
147                         tmp=lp_config_get_string(cfg,logsection,"to",NULL);
148                         if (tmp) cl->to=linphone_address_new(tmp);
149                         tmp=lp_config_get_string(cfg,logsection,"start_date",NULL);
150                         if (tmp) strncpy(cl->start_date,tmp,sizeof(cl->start_date));
151                         cl->duration=lp_config_get_int(cfg,logsection,"duration",0);
152                         tmp=lp_config_get_string(cfg,logsection,"refkey",NULL);
153                         if (tmp) cl->refkey=ms_strdup(tmp);
154                         lc->call_logs=ms_list_append(lc->call_logs,cl);
155                 }else break;    
156         }
157 }
158
159
160
161 /**
162  * @addtogroup call_logs
163  * @{
164 **/
165
166 /**
167  * Returns a human readable string describing the call.
168  * 
169  * @note: the returned char* must be freed by the application (use ms_free()).
170 **/
171 char * linphone_call_log_to_str(LinphoneCallLog *cl){
172         char *status;
173         char *tmp;
174         char *from=linphone_address_as_string (cl->from);
175         char *to=linphone_address_as_string (cl->to);
176         switch(cl->status){
177                 case LinphoneCallAborted:
178                         status=_("aborted");
179                         break;
180                 case LinphoneCallSuccess:
181                         status=_("completed");
182                         break;
183                 case LinphoneCallMissed:
184                         status=_("missed");
185                         break;
186                 default:
187                         status="unknown";
188         }
189         tmp=ortp_strdup_printf(_("%s at %s\nFrom: %s\nTo: %s\nStatus: %s\nDuration: %i mn %i sec\n"),
190                         (cl->dir==LinphoneCallIncoming) ? _("Incoming call") : _("Outgoing call"),
191                         cl->start_date,
192                         from,
193                         to,
194                         status,
195                         cl->duration/60,
196                         cl->duration%60);
197         ms_free(from);
198         ms_free(to);
199         return tmp;
200 }
201
202 /**
203  * Returns RTP statistics computed locally regarding the call.
204  * 
205 **/
206 const rtp_stats_t *linphone_call_log_get_local_stats(const LinphoneCallLog *cl){
207         return &cl->local_stats;
208 }
209
210 /**
211  * Returns RTP statistics computed by remote end and sent back via RTCP.
212  *
213  * @note Not implemented yet.
214 **/
215 const rtp_stats_t *linphone_call_log_get_remote_stats(const LinphoneCallLog *cl){
216         return &cl->remote_stats;
217 }
218
219 void linphone_call_log_set_user_pointer(LinphoneCallLog *cl, void *up){
220         cl->user_pointer=up;
221 }
222
223 void *linphone_call_log_get_user_pointer(const LinphoneCallLog *cl){
224         return cl->user_pointer;
225 }
226
227
228
229 /**
230  * Associate a persistent reference key to the call log.
231  *
232  * The reference key can be for example an id to an external database.
233  * It is stored in the config file, thus can survive to process exits/restarts.
234  *
235 **/
236 void linphone_call_log_set_ref_key(LinphoneCallLog *cl, const char *refkey){
237         if (cl->refkey!=NULL){
238                 ms_free(cl->refkey);
239                 cl->refkey=NULL;
240         }
241         if (refkey) cl->refkey=ms_strdup(refkey);
242         call_logs_write_to_config_file(cl->lc);
243 }
244
245 /**
246  * Get the persistent reference key associated to the call log.
247  *
248  * The reference key can be for example an id to an external database.
249  * It is stored in the config file, thus can survive to process exits/restarts.
250  *
251 **/
252 const char *linphone_call_log_get_ref_key(const LinphoneCallLog *cl){
253         return cl->refkey;
254 }
255
256 /** @} */
257
258 void linphone_call_log_destroy(LinphoneCallLog *cl){
259         if (cl->from!=NULL) linphone_address_destroy(cl->from);
260         if (cl->to!=NULL) linphone_address_destroy(cl->to);
261         if (cl->refkey!=NULL) ms_free(cl->refkey);
262         ms_free(cl);
263 }
264
265 /**
266  * Returns TRUE if the LinphoneCall asked to autoanswer
267  *
268 **/
269 bool_t linphone_call_asked_to_autoanswer(LinphoneCall *call){
270         //return TRUE if the unique(for the moment) incoming call asked to be autoanswered
271         if(call)
272                 return sal_call_autoanswer_asked(call->op);
273         else
274                 return FALSE;
275 }
276
277 int linphone_core_get_current_call_duration(const LinphoneCore *lc){
278         LinphoneCall *call=linphone_core_get_current_call((LinphoneCore *)lc);
279         if (call)  return linphone_call_get_duration(call);
280         return -1;
281 }
282
283 const LinphoneAddress *linphone_core_get_current_call_remote_address(struct _LinphoneCore *lc){
284         LinphoneCall *call=linphone_core_get_current_call(lc);
285         if (call==NULL) return NULL;
286         return linphone_call_get_remote_address(call);
287 }
288
289 /**
290  * Enable logs in supplied FILE*.
291  *
292  * @ingroup misc
293  *
294  * @param file a C FILE* where to fprintf logs. If null stdout is used.
295  * 
296 **/
297 void linphone_core_enable_logs(FILE *file){
298         if (file==NULL) file=stdout;
299         ortp_set_log_file(file);
300         ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
301 }
302
303 /**
304  * Enable logs through the user's supplied log callback.
305  *
306  * @ingroup misc
307  *
308  * @param logfunc The address of a OrtpLogFunc callback whose protoype is
309  *                typedef void (*OrtpLogFunc)(OrtpLogLevel lev, const char *fmt, va_list args);
310  * 
311 **/
312 void linphone_core_enable_logs_with_cb(OrtpLogFunc logfunc){
313         ortp_set_log_level_mask(ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL);
314         ortp_set_log_handler(logfunc);
315 }
316
317 /**
318  * Entirely disable logging.
319  *
320  * @ingroup misc
321 **/
322 void linphone_core_disable_logs(){
323         ortp_set_log_level_mask(ORTP_ERROR|ORTP_FATAL);
324 }
325
326
327 static void net_config_read (LinphoneCore *lc)
328 {
329         int tmp;
330         const char *tmpstr;
331         LpConfig *config=lc->config;
332
333         lc->net_conf.nat_address_ip = NULL;
334         tmp=lp_config_get_int(config,"net","download_bw",0);
335         linphone_core_set_download_bandwidth(lc,tmp);
336         tmp=lp_config_get_int(config,"net","upload_bw",0);
337         linphone_core_set_upload_bandwidth(lc,tmp);
338         linphone_core_set_stun_server(lc,lp_config_get_string(config,"net","stun_server",NULL));
339         tmpstr=lp_config_get_string(lc->config,"net","nat_address",NULL);
340         if (tmpstr!=NULL && (strlen(tmpstr)<1)) tmpstr=NULL;
341         linphone_core_set_nat_address(lc,tmpstr);
342         tmp=lp_config_get_int(lc->config,"net","firewall_policy",0);
343         linphone_core_set_firewall_policy(lc,tmp);
344         tmp=lp_config_get_int(lc->config,"net","nat_sdp_only",0);
345         lc->net_conf.nat_sdp_only=tmp;
346         tmp=lp_config_get_int(lc->config,"net","mtu",0);
347         linphone_core_set_mtu(lc,tmp);
348         tmp=lp_config_get_int(lc->config,"net","download_ptime",0);
349         linphone_core_set_download_ptime(lc,tmp);
350
351 }
352
353 static void build_sound_devices_table(LinphoneCore *lc){
354         const char **devices;
355         const char **old;
356         int ndev;
357         int i;
358         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
359         ndev=ms_list_size(elem);
360         devices=ms_malloc((ndev+1)*sizeof(const char *));
361         for (i=0;elem!=NULL;elem=elem->next,i++){
362                 devices[i]=ms_snd_card_get_string_id((MSSndCard *)elem->data);
363         }
364         devices[ndev]=NULL;
365         old=lc->sound_conf.cards;
366         lc->sound_conf.cards=devices;
367         if (old!=NULL) ms_free(old);
368 }
369
370 static void sound_config_read(LinphoneCore *lc)
371 {
372         int tmp;
373         const char *tmpbuf;
374         const char *devid;
375         float gain=0;
376 #ifdef __linux
377         /*alsadev let the user use custom alsa device within linphone*/
378         devid=lp_config_get_string(lc->config,"sound","alsadev",NULL);
379         if (devid){
380                 MSSndCard *card=ms_alsa_card_new_custom(devid,devid);
381                 ms_snd_card_manager_add_card(ms_snd_card_manager_get(),card);
382         }
383 #endif
384         /* retrieve all sound devices */
385         build_sound_devices_table(lc);
386
387         devid=lp_config_get_string(lc->config,"sound","playback_dev_id",NULL);
388         linphone_core_set_playback_device(lc,devid);
389
390         devid=lp_config_get_string(lc->config,"sound","ringer_dev_id",NULL);
391         linphone_core_set_ringer_device(lc,devid);
392
393         devid=lp_config_get_string(lc->config,"sound","capture_dev_id",NULL);
394         linphone_core_set_capture_device(lc,devid);
395
396 /*
397         tmp=lp_config_get_int(lc->config,"sound","play_lev",80);
398         linphone_core_set_play_level(lc,tmp);
399         tmp=lp_config_get_int(lc->config,"sound","ring_lev",80);
400         linphone_core_set_ring_level(lc,tmp);
401         tmp=lp_config_get_int(lc->config,"sound","rec_lev",80);
402         linphone_core_set_rec_level(lc,tmp);
403         tmpbuf=lp_config_get_string(lc->config,"sound","source","m");
404         linphone_core_set_sound_source(lc,tmpbuf[0]);
405 */
406
407         tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
408         tmpbuf=lp_config_get_string(lc->config,"sound","local_ring",tmpbuf);
409         if (ortp_file_exist(tmpbuf)==-1) {
410                 ms_warning("%s does not exist",tmpbuf);
411                 tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
412         }
413         if (strstr(tmpbuf,".wav")==NULL){
414                 /* it currently uses old sound files, so replace them */
415                 tmpbuf=PACKAGE_SOUND_DIR "/" LOCAL_RING;
416         }
417         linphone_core_set_ring(lc,tmpbuf);
418
419         tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
420         tmpbuf=lp_config_get_string(lc->config,"sound","remote_ring",tmpbuf);
421         if (ortp_file_exist(tmpbuf)==-1){
422                 tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
423         }
424         if (strstr(tmpbuf,".wav")==NULL){
425                 /* it currently uses old sound files, so replace them */
426                 tmpbuf=PACKAGE_SOUND_DIR "/" REMOTE_RING;
427         }
428         linphone_core_set_ringback(lc,tmpbuf);
429
430         linphone_core_set_play_file(lc,lp_config_get_string(lc->config,"sound","hold_music",PACKAGE_SOUND_DIR "/" HOLD_MUSIC));
431         check_sound_device(lc);
432         lc->sound_conf.latency=0;
433 #if !defined(TARGET_OS_IPHONE) && !defined(ANDROID)
434     tmp=TRUE;
435 #else 
436     tmp=FALSE;
437 #endif
438     tmp=lp_config_get_int(lc->config,"sound","echocancellation",tmp);
439         linphone_core_enable_echo_cancellation(lc,tmp);
440         linphone_core_enable_echo_limiter(lc,
441                 lp_config_get_int(lc->config,"sound","echolimiter",0));
442         linphone_core_enable_agc(lc,
443                 lp_config_get_int(lc->config,"sound","agc",0));
444
445         gain=lp_config_get_float(lc->config,"sound","playback_gain_db",0);
446         linphone_core_set_playback_gain_db (lc,gain);
447
448         linphone_core_set_remote_ringback_tone (lc,lp_config_get_string(lc->config,"sound","ringback_tone",NULL));
449 }
450
451 static void sip_config_read(LinphoneCore *lc)
452 {
453         char *contact;
454         const char *tmpstr;
455         LCSipTransports tr;
456         int i,tmp;
457         int ipv6;
458
459         tmp=lp_config_get_int(lc->config,"sip","use_info",0);
460         linphone_core_set_use_info_for_dtmf(lc,tmp);
461
462         if (lp_config_get_int(lc->config,"sip","use_session_timers",0)==1){
463                 sal_use_session_timers(lc->sal,200);
464         }
465
466         sal_use_rport(lc->sal,lp_config_get_int(lc->config,"sip","use_rport",1));
467         sal_use_101(lc->sal,lp_config_get_int(lc->config,"sip","use_101",1));
468
469         tmp=lp_config_get_int(lc->config,"sip","use_rfc2833",0);
470         linphone_core_set_use_rfc2833_for_dtmf(lc,tmp);
471
472         ipv6=lp_config_get_int(lc->config,"sip","use_ipv6",-1);
473         if (ipv6==-1){
474                 ipv6=0;
475         }
476         linphone_core_enable_ipv6(lc,ipv6);
477         memset(&tr,0,sizeof(tr));
478         if (lp_config_get_int(lc->config,"sip","sip_random_port",0)) {
479                 tr.udp_port=(0xDFF&+random())+1024;
480         } else {
481                 tr.udp_port=lp_config_get_int(lc->config,"sip","sip_port",5060);
482         }
483         if (lp_config_get_int(lc->config,"sip","sip_tcp_random_port",0)) {
484                 tr.tcp_port=(0xDFF&+random())+1024;
485         } else {
486                 tr.tcp_port=lp_config_get_int(lc->config,"sip","sip_tcp_port",0);
487         }
488         /*start listening on ports*/
489         linphone_core_set_sip_transports(lc,&tr);
490
491         tmpstr=lp_config_get_string(lc->config,"sip","contact",NULL);
492         if (tmpstr==NULL || linphone_core_set_primary_contact(lc,tmpstr)==-1) {
493                 const char *hostname=NULL;
494                 const char *username=NULL;
495 #ifdef HAVE_GETENV
496                 hostname=getenv("HOST");
497                 username=getenv("USER");
498                 if (hostname==NULL) hostname=getenv("HOSTNAME");
499 #endif /*HAVE_GETENV*/
500                 if (hostname==NULL)
501                         hostname="unknown-host";
502                 if (username==NULL){
503                         username="toto";
504                 }
505                 contact=ortp_strdup_printf("sip:%s@%s",username,hostname);
506                 linphone_core_set_primary_contact(lc,contact);
507                 ms_free(contact);
508         }
509
510         tmp=lp_config_get_int(lc->config,"sip","guess_hostname",1);
511         linphone_core_set_guess_hostname(lc,tmp);
512
513
514         tmp=lp_config_get_int(lc->config,"sip","inc_timeout",15);
515         linphone_core_set_inc_timeout(lc,tmp);
516
517         /* get proxies config */
518         for(i=0;; i++){
519                 LinphoneProxyConfig *cfg=linphone_proxy_config_new_from_config_file(lc->config,i);
520                 if (cfg!=NULL){
521                         linphone_core_add_proxy_config(lc,cfg);
522                 }else{
523                         break;
524                 }
525         }
526         /* get the default proxy */
527         tmp=lp_config_get_int(lc->config,"sip","default_proxy",-1);
528         linphone_core_set_default_proxy_index(lc,tmp);
529
530         /* read authentication information */
531         for(i=0;; i++){
532                 LinphoneAuthInfo *ai=linphone_auth_info_new_from_config_file(lc->config,i);
533                 if (ai!=NULL){
534                         linphone_core_add_auth_info(lc,ai);
535                         linphone_auth_info_destroy(ai);
536                 }else{
537                         break;
538                 }
539         }
540         
541         /*for tuning or test*/
542         lc->sip_conf.sdp_200_ack=lp_config_get_int(lc->config,"sip","sdp_200_ack",0);
543         lc->sip_conf.register_only_when_network_is_up=
544                 lp_config_get_int(lc->config,"sip","register_only_when_network_is_up",1);
545         lc->sip_conf.ping_with_options=lp_config_get_int(lc->config,"sip","ping_with_options",1);
546         lc->sip_conf.auto_net_state_mon=lp_config_get_int(lc->config,"sip","auto_net_state_mon",1);
547         lc->sip_conf.keepalive_period=lp_config_get_int(lc->config,"sip","keepalive_period",10000);
548         sal_set_keepalive_period(lc->sal,lc->sip_conf.keepalive_period);
549         sal_use_one_matching_codec_policy(lc->sal,lp_config_get_int(lc->config,"sip","only_one_codec",0));
550         sal_use_double_registrations(lc->sal,lp_config_get_int(lc->config,"sip","use_double_registrations",1));
551 }
552
553 static void rtp_config_read(LinphoneCore *lc)
554 {
555         int port;
556         int jitt_comp;
557         int nortp_timeout;
558         bool_t rtp_no_xmit_on_audio_mute;
559
560         port=lp_config_get_int(lc->config,"rtp","audio_rtp_port",7078);
561         linphone_core_set_audio_port(lc,port);
562
563         port=lp_config_get_int(lc->config,"rtp","video_rtp_port",9078);
564         if (port==0) port=9078;
565         linphone_core_set_video_port(lc,port);
566
567         jitt_comp=lp_config_get_int(lc->config,"rtp","audio_jitt_comp",60);
568         linphone_core_set_audio_jittcomp(lc,jitt_comp);
569         jitt_comp=lp_config_get_int(lc->config,"rtp","video_jitt_comp",60);
570         if (jitt_comp==0) jitt_comp=60;
571         lc->rtp_conf.video_jitt_comp=jitt_comp;
572         nortp_timeout=lp_config_get_int(lc->config,"rtp","nortp_timeout",30);
573         linphone_core_set_nortp_timeout(lc,nortp_timeout);
574         rtp_no_xmit_on_audio_mute=lp_config_get_int(lc->config,"rtp","rtp_no_xmit_on_audio_mute",FALSE);
575         linphone_core_set_rtp_no_xmit_on_audio_mute(lc,rtp_no_xmit_on_audio_mute);      
576 }
577
578 static PayloadType * find_payload(RtpProfile *prof, const char *mime_type, int clock_rate, const char *recv_fmtp){
579         PayloadType *candidate=NULL;
580         int i;
581         PayloadType *it;
582         for(i=0;i<127;++i){
583                 it=rtp_profile_get_payload(prof,i);
584                 if (it!=NULL && strcasecmp(mime_type,it->mime_type)==0
585                         && (clock_rate==it->clock_rate || clock_rate<=0) ){
586                         if ( (recv_fmtp && it->recv_fmtp && strstr(recv_fmtp,it->recv_fmtp)!=NULL) ||
587                                 (recv_fmtp==NULL && it->recv_fmtp==NULL) ){
588                                 /*exact match*/
589                                 if (recv_fmtp) payload_type_set_recv_fmtp(it,recv_fmtp);
590                                 return it;
591                         }else {
592                                 if (candidate){
593                                         if (it->recv_fmtp==NULL) candidate=it;
594                                 }else candidate=it;
595                         }
596                 }
597         }
598         if (candidate && recv_fmtp){
599                 payload_type_set_recv_fmtp(candidate,recv_fmtp);
600         }
601         return candidate;
602 }
603
604 static bool_t get_codec(LpConfig *config, const char* type, int index, PayloadType **ret){
605         char codeckey[50];
606         const char *mime,*fmtp;
607         int rate,enabled;
608         PayloadType *pt;
609
610         *ret=NULL;
611         snprintf(codeckey,50,"%s_%i",type,index);
612         mime=lp_config_get_string(config,codeckey,"mime",NULL);
613         if (mime==NULL || strlen(mime)==0 ) return FALSE;
614
615         rate=lp_config_get_int(config,codeckey,"rate",8000);
616         fmtp=lp_config_get_string(config,codeckey,"recv_fmtp",NULL);
617         enabled=lp_config_get_int(config,codeckey,"enabled",1);
618         pt=find_payload(&av_profile,mime,rate,fmtp);
619         if (pt && enabled ) pt->flags|=PAYLOAD_TYPE_ENABLED;
620         //ms_message("Found codec %s/%i",pt->mime_type,pt->clock_rate);
621         if (pt==NULL) ms_warning("Ignoring codec config %s/%i with fmtp=%s because unsupported",
622                         mime,rate,fmtp ? fmtp : "");
623         *ret=pt;
624         return TRUE;
625 }
626
627 static const char *codec_pref_order[]={
628         "speex",
629         "gsm",
630         "pcmu",
631         "pcma",
632         "H264",
633         "MP4V-ES",
634         "theora",
635         "H263-1998",
636         "H263",
637         "x-snow",
638         NULL,
639 };
640
641 static int find_codec_rank(const char *mime){
642         int i;
643         for(i=0;codec_pref_order[i]!=NULL;++i){
644                 if (strcasecmp(codec_pref_order[i],mime)==0)
645                         break;
646         }
647         return i;
648 }
649
650 static int codec_compare(const PayloadType *a, const PayloadType *b){
651         int ra,rb;
652         ra=find_codec_rank(a->mime_type);
653         rb=find_codec_rank(b->mime_type);
654         if (ra>rb) return 1;
655         if (ra<rb) return -1;
656         return 0;
657 }
658
659 static MSList *add_missing_codecs(SalStreamType mtype, MSList *l){
660         int i;
661         for(i=0;i<127;++i){
662                 PayloadType *pt=rtp_profile_get_payload(&av_profile,i);
663                 if (pt){
664                         if (mtype==SalVideo && pt->type!=PAYLOAD_VIDEO)
665                                 pt=NULL;
666                         else if (mtype==SalAudio && (pt->type!=PAYLOAD_AUDIO_PACKETIZED 
667                             && pt->type!=PAYLOAD_AUDIO_CONTINUOUS)){
668                                 pt=NULL;
669                         }
670                         if (pt && ms_filter_codec_supported(pt->mime_type)){
671                                 if (ms_list_find(l,pt)==NULL){
672                                         /*do not enable old or experimental codecs by default*/
673                                         if (strcasecmp(pt->mime_type,"H263")!=0 && strcasecmp(pt->mime_type,"x-snow")!=0){
674                                                 payload_type_set_flag(pt,PAYLOAD_TYPE_ENABLED);
675                                         }
676                                         ms_message("Adding new codec %s/%i with fmtp %s",
677                                             pt->mime_type,pt->clock_rate,pt->recv_fmtp ? pt->recv_fmtp : "");
678                                         l=ms_list_insert_sorted(l,pt,(int (*)(const void *, const void *))codec_compare);
679                                 }
680                         }
681                 }
682         }
683         return l;
684 }
685
686 static MSList *codec_append_if_new(MSList *l, PayloadType *pt){
687         MSList *elem;
688         for (elem=l;elem!=NULL;elem=elem->next){
689                 PayloadType *ept=(PayloadType*)elem->data;
690                 if (pt==ept)
691                         return l;
692         }
693         l=ms_list_append(l,pt);
694         return l;
695 }
696
697 static void codecs_config_read(LinphoneCore *lc)
698 {
699         int i;
700         PayloadType *pt;
701         MSList *audio_codecs=NULL;
702         MSList *video_codecs=NULL;
703         for (i=0;get_codec(lc->config,"audio_codec",i,&pt);i++){
704                 if (pt){
705                         if (!ms_filter_codec_supported(pt->mime_type)){
706                                 ms_warning("Codec %s is not supported by mediastreamer2, removed.",pt->mime_type);
707                         }else audio_codecs=codec_append_if_new(audio_codecs,pt);
708                 }
709         }
710         audio_codecs=add_missing_codecs(SalAudio,audio_codecs);
711         for (i=0;get_codec(lc->config,"video_codec",i,&pt);i++){
712                 if (pt){
713                         if (!ms_filter_codec_supported(pt->mime_type)){
714                                 ms_warning("Codec %s is not supported by mediastreamer2, removed.",pt->mime_type);
715                         }else video_codecs=codec_append_if_new(video_codecs,(void *)pt);
716                 }
717         }
718         video_codecs=add_missing_codecs(SalVideo,video_codecs);
719         linphone_core_set_audio_codecs(lc,audio_codecs);
720         linphone_core_set_video_codecs(lc,video_codecs);
721         linphone_core_update_allocated_audio_bandwidth(lc);
722 }
723
724 static void video_config_read(LinphoneCore *lc){
725         int capture, display, self_view;
726         const char *str;
727         int ndev;
728         const char **devices;
729         const MSList *elem;
730         int i;
731
732         /* retrieve all video devices */
733         elem=ms_web_cam_manager_get_list(ms_web_cam_manager_get());
734         ndev=ms_list_size(elem);
735         devices=ms_malloc((ndev+1)*sizeof(const char *));
736         for (i=0;elem!=NULL;elem=elem->next,i++){
737                 devices[i]=ms_web_cam_get_string_id((MSWebCam *)elem->data);
738         }
739         devices[ndev]=NULL;
740         lc->video_conf.cams=devices;
741
742         str=lp_config_get_string(lc->config,"video","device",NULL);
743         if (str && str[0]==0) str=NULL;
744         linphone_core_set_video_device(lc,str);
745
746         linphone_core_set_preferred_video_size_by_name(lc,
747                 lp_config_get_string(lc->config,"video","size","cif"));
748
749         capture=lp_config_get_int(lc->config,"video","capture",1);
750         display=lp_config_get_int(lc->config,"video","display",1);
751         self_view=lp_config_get_int(lc->config,"video","self_view",1);
752         lc->video_conf.displaytype=lp_config_get_string(lc->config,"video","displaytype",NULL);
753         if(lc->video_conf.displaytype)
754                 ms_message("we are using a specific display:%s\n",lc->video_conf.displaytype);
755 #ifdef VIDEO_ENABLED
756         linphone_core_enable_video(lc,capture,display);
757         linphone_core_enable_self_view(lc,self_view);
758 #endif
759 }
760
761 static void ui_config_read(LinphoneCore *lc)
762 {
763         LinphoneFriend *lf;
764         int i;
765         for (i=0;(lf=linphone_friend_new_from_config_file(lc,i))!=NULL;i++){
766                 linphone_core_add_friend(lc,lf);
767         }
768         call_logs_read_from_config_file(lc);
769 }
770
771 /*
772 static void autoreplier_config_init(LinphoneCore *lc)
773 {
774         autoreplier_config_t *config=&lc->autoreplier_conf;
775         config->enabled=lp_config_get_int(lc->config,"autoreplier","enabled",0);
776         config->after_seconds=lp_config_get_int(lc->config,"autoreplier","after_seconds",6);
777         config->max_users=lp_config_get_int(lc->config,"autoreplier","max_users",1);
778         config->max_rec_time=lp_config_get_int(lc->config,"autoreplier","max_rec_time",60);
779         config->max_rec_msg=lp_config_get_int(lc->config,"autoreplier","max_rec_msg",10);
780         config->message=lp_config_get_string(lc->config,"autoreplier","message",NULL);
781 }
782 */
783
784 /**
785  * Sets maximum available download bandwidth
786  *
787  * @ingroup media_parameters
788  *
789  * This is IP bandwidth, in kbit/s.
790  * This information is used signaled to other parties during
791  * calls (within SDP messages) so that the remote end can have
792  * sufficient knowledge to properly configure its audio & video
793  * codec output bitrate to not overflow available bandwidth.
794  *
795  * @param lc the LinphoneCore object
796  * @param bw the bandwidth in kbits/s, 0 for infinite
797  */
798 void linphone_core_set_download_bandwidth(LinphoneCore *lc, int bw){
799         lc->net_conf.download_bw=bw;
800 }
801
802 /**
803  * Sets maximum available upload bandwidth
804  *
805  * @ingroup media_parameters
806  *
807  * This is IP bandwidth, in kbit/s.
808  * This information is used by liblinphone together with remote
809  * side available bandwidth signaled in SDP messages to properly
810  * configure audio & video codec's output bitrate.
811  *
812  * @param lc the LinphoneCore object
813  * @param bw the bandwidth in kbits/s, 0 for infinite
814  */
815 void linphone_core_set_upload_bandwidth(LinphoneCore *lc, int bw){
816         lc->net_conf.upload_bw=bw;
817 }
818
819 /**
820  * Retrieve the maximum available download bandwidth.
821  *
822  * @ingroup media_parameters
823  *
824  * This value was set by linphone_core_set_download_bandwidth().
825  *
826 **/
827 int linphone_core_get_download_bandwidth(const LinphoneCore *lc){
828         return lc->net_conf.download_bw;
829 }
830
831 /**
832  * Retrieve the maximum available upload bandwidth.
833  *
834  * @ingroup media_parameters
835  *
836  * This value was set by linphone_core_set_upload_bandwidth().
837  *
838 **/
839 int linphone_core_get_upload_bandwidth(const LinphoneCore *lc){
840         return lc->net_conf.upload_bw;
841 }
842 /**
843  * set audio packetization time linphone expect to received from peer
844  */
845 void linphone_core_set_download_ptime(LinphoneCore *lc, int ptime) {
846         lc->net_conf.down_ptime=ptime;
847 }
848
849 int  linphone_core_get_download_ptime(LinphoneCore *lc) {
850         return lc->net_conf.down_ptime;
851 }
852
853
854 /**
855  * Returns liblinphone's version as a string.
856  *
857  * @ingroup misc
858  *
859 **/
860 const char * linphone_core_get_version(void){
861         return liblinphone_version;
862 }
863
864
865 static MSList *linphone_payload_types=NULL;
866
867 static void linphone_core_assign_payload_type(PayloadType *const_pt, int number, const char *recv_fmtp){
868         PayloadType *pt;
869         pt=payload_type_clone(const_pt);
870         payload_type_set_number(pt,number);
871         if (recv_fmtp!=NULL) payload_type_set_recv_fmtp(pt,recv_fmtp);
872         rtp_profile_set_payload(&av_profile,number,pt);
873         linphone_payload_types=ms_list_append(linphone_payload_types,pt);
874 }
875
876 static void linphone_core_free_payload_types(void){
877         ms_list_for_each(linphone_payload_types,(void (*)(void*))payload_type_destroy);
878         ms_list_free(linphone_payload_types);
879         linphone_payload_types=NULL;
880 }
881
882 void linphone_core_set_state(LinphoneCore *lc, LinphoneGlobalState gstate, const char *message){
883         lc->state=gstate;
884         if (lc->vtable.global_state_changed){
885                 lc->vtable.global_state_changed(lc,gstate,message);
886         }
887 }
888 static void misc_config_read (LinphoneCore *lc) {
889         LpConfig *config=lc->config;
890     lc->max_call_logs=lp_config_get_int(config,"misc","history_max_size",15);
891 }
892
893 static void linphone_core_init (LinphoneCore * lc, const LinphoneCoreVTable *vtable, const char *config_path, 
894     const char *factory_config_path, void * userdata)
895 {
896         memset (lc, 0, sizeof (LinphoneCore));
897         lc->data=userdata;
898         lc->ringstream_autorelease=TRUE;
899         
900         memcpy(&lc->vtable,vtable,sizeof(LinphoneCoreVTable));
901
902         linphone_core_set_state(lc,LinphoneGlobalStartup,"Starting up");
903         ortp_init();
904         linphone_core_assign_payload_type(&payload_type_pcmu8000,0,NULL);
905         linphone_core_assign_payload_type(&payload_type_gsm,3,NULL);
906         linphone_core_assign_payload_type(&payload_type_pcma8000,8,NULL);
907         linphone_core_assign_payload_type(&payload_type_lpc1015,115,NULL);
908         linphone_core_assign_payload_type(&payload_type_speex_nb,110,"vbr=on");
909         linphone_core_assign_payload_type(&payload_type_speex_wb,111,"vbr=on");
910         linphone_core_assign_payload_type(&payload_type_speex_uwb,112,"vbr=on");
911         linphone_core_assign_payload_type(&payload_type_telephone_event,101,"0-11");
912         linphone_core_assign_payload_type(&payload_type_ilbc,113,"mode=30");
913         linphone_core_assign_payload_type(&payload_type_amr,114,"octet-align=1");
914
915 #if defined(ANDROID) || defined (__IPHONE_OS_VERSION_MIN_REQUIRED)
916         /*shorten the DNS lookup time and send more retransmissions on mobiles:
917          - to workaround potential packet losses
918          - to avoid hanging for 30 seconds when the network doesn't work despite the phone thinks it does.
919          */
920         _linphone_core_configure_resolver();
921 #endif
922
923 #ifdef ENABLE_NONSTANDARD_GSM
924         {
925                 PayloadType *pt;
926                 pt=payload_type_clone(&payload_type_gsm);
927                 pt->clock_rate=11025;
928                 rtp_profile_set_payload(&av_profile,114,pt);
929                 linphone_payload_types=ms_list_append(linphone_payload_types,pt);
930                 pt=payload_type_clone(&payload_type_gsm);
931                 pt->clock_rate=22050;
932                 rtp_profile_set_payload(&av_profile,115,pt);
933                 linphone_payload_types=ms_list_append(linphone_payload_types,pt);
934         }
935 #endif
936
937 #ifdef VIDEO_ENABLED
938         linphone_core_assign_payload_type(&payload_type_h263,34,NULL);
939         linphone_core_assign_payload_type(&payload_type_theora,97,NULL);
940         linphone_core_assign_payload_type(&payload_type_h263_1998,98,"CIF=1;QCIF=1");
941         linphone_core_assign_payload_type(&payload_type_mp4v,99,"profile-level-id=3");
942         linphone_core_assign_payload_type(&payload_type_x_snow,100,NULL);
943         linphone_core_assign_payload_type(&payload_type_h264,102,"profile-level-id=428014");
944         /* due to limited space in SDP, we have to disable this h264 line which is normally no more necessary */
945         /* linphone_core_assign_payload_type(&payload_type_h264,103,"packetization-mode=1;profile-level-id=428014");*/
946 #endif
947
948         ms_init();
949         /* create a mediastreamer2 event queue and set it as global */
950         /* This allows to run event's callback in linphone_core_iterate() */
951         lc->msevq=ms_event_queue_new();
952         ms_set_global_event_queue(lc->msevq);
953
954         lc->config=lp_config_new(config_path);
955         if (factory_config_path)
956                 lp_config_read_file(lc->config,factory_config_path);
957
958         lc->sal=sal_init();
959         sal_set_user_pointer(lc->sal,lc);
960         sal_set_callbacks(lc->sal,&linphone_sal_callbacks);
961         
962         sip_setup_register_all();
963         sound_config_read(lc);
964         net_config_read(lc);
965         rtp_config_read(lc);
966         codecs_config_read(lc);
967         sip_config_read(lc); /* this will start eXosip*/
968         video_config_read(lc);
969         //autoreplier_config_init(&lc->autoreplier_conf);
970         lc->presence_mode=LinphoneStatusOnline;
971         misc_config_read(lc);
972         ui_config_read(lc);
973         if (lc->vtable.display_status)
974                 lc->vtable.display_status(lc,_("Ready"));
975         lc->auto_net_state_mon=lc->sip_conf.auto_net_state_mon;
976         linphone_core_set_state(lc,LinphoneGlobalOn,"Ready");
977 }
978
979 /**
980  * Instanciates a LinphoneCore object.
981  * @ingroup initializing
982  * 
983  * The LinphoneCore object is the primary handle for doing all phone actions.
984  * It should be unique within your application.
985  * @param vtable a LinphoneCoreVTable structure holding your application callbacks
986  * @param config_path a path to a config file. If it does not exists it will be created.
987  *        The config file is used to store all settings, call logs, friends, proxies... so that all these settings
988  *             become persistent over the life of the LinphoneCore object.
989  *             It is allowed to set a NULL config file. In that case LinphoneCore will not store any settings.
990  * @param factory_config_path a path to a read-only config file that can be used to 
991  *        to store hard-coded preference such as proxy settings or internal preferences.
992  *        The settings in this factory file always override the one in the normal config file.
993  *        It is OPTIONAL, use NULL if unneeded.
994  * @param userdata an opaque user pointer that can be retrieved at any time (for example in
995  *        callbacks) using linphone_core_get_user_data().
996  * 
997 **/
998 LinphoneCore *linphone_core_new(const LinphoneCoreVTable *vtable,
999                                                 const char *config_path, const char *factory_config_path, void * userdata)
1000 {
1001         LinphoneCore *core=ms_new(LinphoneCore,1);
1002         linphone_core_init(core,vtable,config_path, factory_config_path, userdata);
1003         return core;
1004 }
1005
1006 /**
1007  * Returns the list of available audio codecs.
1008  *
1009  * This list is unmodifiable. The ->data field of the MSList points a PayloadType
1010  * structure holding the codec information.
1011  * It is possible to make copy of the list with ms_list_copy() in order to modify it
1012  * (such as the order of codecs).
1013 **/
1014 const MSList *linphone_core_get_audio_codecs(const LinphoneCore *lc)
1015 {
1016         return lc->codecs_conf.audio_codecs;
1017 }
1018
1019 /**
1020  * Returns the list of available video codecs.
1021  *
1022  * This list is unmodifiable. The ->data field of the MSList points a PayloadType
1023  * structure holding the codec information.
1024  * It is possible to make copy of the list with ms_list_copy() in order to modify it
1025  * (such as the order of codecs).
1026 **/
1027 const MSList *linphone_core_get_video_codecs(const LinphoneCore *lc)
1028 {
1029         return lc->codecs_conf.video_codecs;
1030 }
1031
1032 /**
1033  * Sets the local "from" identity.
1034  *
1035  * @ingroup proxies
1036  * This data is used in absence of any proxy configuration or when no
1037  * default proxy configuration is set. See LinphoneProxyConfig
1038 **/
1039 int linphone_core_set_primary_contact(LinphoneCore *lc, const char *contact)
1040 {
1041         LinphoneAddress *ctt;
1042
1043         if ((ctt=linphone_address_new(contact))==0) {
1044                 ms_error("Bad contact url: %s",contact);
1045                 return -1;
1046         }
1047         if (lc->sip_conf.contact!=NULL) ms_free(lc->sip_conf.contact);
1048         lc->sip_conf.contact=ms_strdup(contact);
1049         if (lc->sip_conf.guessed_contact!=NULL){
1050                 ms_free(lc->sip_conf.guessed_contact);
1051                 lc->sip_conf.guessed_contact=NULL;
1052         }
1053         linphone_address_destroy(ctt);
1054         return 0;
1055 }
1056
1057
1058 /*result must be an array of chars at least LINPHONE_IPADDR_SIZE */
1059 void linphone_core_get_local_ip(LinphoneCore *lc, const char *dest, char *result){
1060         const char *ip;
1061         if (linphone_core_get_firewall_policy(lc)==LinphonePolicyUseNatAddress
1062             && (ip=linphone_core_get_nat_address_resolved(lc))!=NULL){
1063                 strncpy(result,ip,LINPHONE_IPADDR_SIZE);
1064                 return;
1065         }
1066         if (linphone_core_get_local_ip_for(lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,dest,result)==0)
1067                 return;
1068         /*else fallback to SAL routine that will attempt to find the most realistic interface */
1069         sal_get_default_local_ip(lc->sal,lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,result,LINPHONE_IPADDR_SIZE);
1070 }
1071
1072 static void update_primary_contact(LinphoneCore *lc){
1073         char *guessed=NULL;
1074         char tmp[LINPHONE_IPADDR_SIZE];
1075
1076         LinphoneAddress *url;
1077         if (lc->sip_conf.guessed_contact!=NULL){
1078                 ms_free(lc->sip_conf.guessed_contact);
1079                 lc->sip_conf.guessed_contact=NULL;
1080         }
1081         url=linphone_address_new(lc->sip_conf.contact);
1082         if (!url){
1083                 ms_error("Could not parse identity contact !");
1084                 url=linphone_address_new("sip:unknown@unkwownhost");
1085         }
1086         linphone_core_get_local_ip(lc, NULL, tmp);
1087         if (strcmp(tmp,"127.0.0.1")==0 || strcmp(tmp,"::1")==0 ){
1088                 ms_warning("Local loopback network only !");
1089                 lc->sip_conf.loopback_only=TRUE;
1090         }else lc->sip_conf.loopback_only=FALSE;
1091         linphone_address_set_domain(url,tmp);
1092         linphone_address_set_port_int(url,linphone_core_get_sip_port (lc));
1093         guessed=linphone_address_as_string(url);
1094         lc->sip_conf.guessed_contact=guessed;
1095         linphone_address_destroy(url);
1096 }
1097
1098 /**
1099  * Returns the default identity when no proxy configuration is used.
1100  *
1101  * @ingroup proxies
1102 **/
1103 const char *linphone_core_get_primary_contact(LinphoneCore *lc){
1104         char *identity;
1105         
1106         if (lc->sip_conf.guess_hostname){
1107                 if (lc->sip_conf.guessed_contact==NULL || lc->sip_conf.loopback_only){
1108                         update_primary_contact(lc);
1109                 }
1110                 identity=lc->sip_conf.guessed_contact;
1111         }else{
1112                 identity=lc->sip_conf.contact;
1113         }
1114         return identity;
1115 }
1116
1117 /**
1118  * Tells LinphoneCore to guess local hostname automatically in primary contact.
1119  *
1120  * @ingroup proxies
1121 **/
1122 void linphone_core_set_guess_hostname(LinphoneCore *lc, bool_t val){
1123         lc->sip_conf.guess_hostname=val;
1124 }
1125
1126 /**
1127  * Returns TRUE if hostname part of primary contact is guessed automatically.
1128  *
1129  * @ingroup proxies
1130 **/
1131 bool_t linphone_core_get_guess_hostname(LinphoneCore *lc){
1132         return lc->sip_conf.guess_hostname;
1133 }
1134
1135 /**
1136  * Same as linphone_core_get_primary_contact() but the result is a LinphoneAddress object
1137  * instead of const char*
1138  *
1139  * @ingroup proxies
1140 **/
1141 LinphoneAddress *linphone_core_get_primary_contact_parsed(LinphoneCore *lc){
1142         return linphone_address_new(linphone_core_get_primary_contact(lc));
1143 }
1144
1145 /**
1146  * Sets the list of audio codecs.
1147  *
1148  * @ingroup media_parameters
1149  * The list is taken by the LinphoneCore thus the application should not free it.
1150  * This list is made of struct PayloadType describing the codec parameters.
1151 **/
1152 int linphone_core_set_audio_codecs(LinphoneCore *lc, MSList *codecs)
1153 {
1154         if (lc->codecs_conf.audio_codecs!=NULL) ms_list_free(lc->codecs_conf.audio_codecs);
1155         lc->codecs_conf.audio_codecs=codecs;
1156         return 0;
1157 }
1158
1159 /**
1160  * Sets the list of video codecs.
1161  *
1162  * @ingroup media_parameters
1163  * The list is taken by the LinphoneCore thus the application should not free it.
1164  * This list is made of struct PayloadType describing the codec parameters.
1165 **/
1166 int linphone_core_set_video_codecs(LinphoneCore *lc, MSList *codecs)
1167 {
1168         if (lc->codecs_conf.video_codecs!=NULL) ms_list_free(lc->codecs_conf.video_codecs);
1169         lc->codecs_conf.video_codecs=codecs;
1170         return 0;
1171 }
1172
1173 const MSList * linphone_core_get_friend_list(const LinphoneCore *lc)
1174 {
1175         return lc->friends;
1176 }
1177
1178 /**
1179  * Returns the nominal jitter buffer size in milliseconds.
1180  *
1181  * @ingroup media_parameters
1182 **/
1183 int linphone_core_get_audio_jittcomp(LinphoneCore *lc)
1184 {
1185         return lc->rtp_conf.audio_jitt_comp;
1186 }
1187
1188 /**
1189  * Returns the UDP port used for audio streaming.
1190  *
1191  * @ingroup network_parameters
1192 **/
1193 int linphone_core_get_audio_port(const LinphoneCore *lc)
1194 {
1195         return lc->rtp_conf.audio_rtp_port;
1196 }
1197
1198 /**
1199  * Returns the UDP port used for video streaming.
1200  *
1201  * @ingroup network_parameters
1202 **/
1203 int linphone_core_get_video_port(const LinphoneCore *lc){
1204         return lc->rtp_conf.video_rtp_port;
1205 }
1206
1207
1208 /**
1209  * Returns the value in seconds of the no-rtp timeout.
1210  *
1211  * @ingroup media_parameters
1212  * When no RTP or RTCP packets have been received for a while
1213  * LinphoneCore will consider the call is broken (remote end crashed or
1214  * disconnected from the network), and thus will terminate the call.
1215  * The no-rtp timeout is the duration above which the call is considered broken.
1216 **/
1217 int linphone_core_get_nortp_timeout(const LinphoneCore *lc){
1218         return lc->rtp_conf.nortp_timeout;
1219 }
1220
1221 bool_t linphone_core_get_rtp_no_xmit_on_audio_mute(const LinphoneCore *lc){
1222         return lc->rtp_conf.rtp_no_xmit_on_audio_mute;
1223 }
1224
1225 /**
1226  * Sets the nominal audio jitter buffer size in milliseconds.
1227  *
1228  * @ingroup media_parameters
1229 **/
1230 void linphone_core_set_audio_jittcomp(LinphoneCore *lc, int value)
1231 {
1232         lc->rtp_conf.audio_jitt_comp=value;
1233 }
1234
1235 void linphone_core_set_rtp_no_xmit_on_audio_mute(LinphoneCore *lc,bool_t rtp_no_xmit_on_audio_mute){
1236         lc->rtp_conf.rtp_no_xmit_on_audio_mute=rtp_no_xmit_on_audio_mute;
1237 }
1238
1239 /**
1240  * Sets the UDP port used for audio streaming.
1241  *
1242  * @ingroup network_parameters
1243 **/
1244 void linphone_core_set_audio_port(LinphoneCore *lc, int port)
1245 {
1246         lc->rtp_conf.audio_rtp_port=port;
1247 }
1248
1249 /**
1250  * Sets the UDP port used for video streaming.
1251  *
1252  * @ingroup network_parameters
1253 **/
1254 void linphone_core_set_video_port(LinphoneCore *lc, int port){
1255         lc->rtp_conf.video_rtp_port=port;
1256 }
1257
1258 /**
1259  * Sets the no-rtp timeout value in seconds.
1260  * 
1261  * @ingroup media_parameters
1262  * See linphone_core_get_nortp_timeout() for details.
1263 **/
1264 void linphone_core_set_nortp_timeout(LinphoneCore *lc, int nortp_timeout){
1265         lc->rtp_conf.nortp_timeout=nortp_timeout;
1266 }
1267
1268 /**
1269  * Indicates whether SIP INFO is used for sending digits.
1270  *
1271  * @ingroup media_parameters
1272 **/
1273 bool_t linphone_core_get_use_info_for_dtmf(LinphoneCore *lc)
1274 {
1275         return lc->sip_conf.use_info;
1276 }
1277
1278 /**
1279  * Sets whether SIP INFO is to be used for sending digits.
1280  *
1281  * @ingroup media_parameters
1282 **/
1283 void linphone_core_set_use_info_for_dtmf(LinphoneCore *lc,bool_t use_info)
1284 {
1285         lc->sip_conf.use_info=use_info;
1286 }
1287
1288 /**
1289  * Indicates whether RFC2833 is used for sending digits.
1290  *
1291  * @ingroup media_parameters
1292 **/
1293 bool_t linphone_core_get_use_rfc2833_for_dtmf(LinphoneCore *lc)
1294 {
1295         return lc->sip_conf.use_rfc2833;
1296 }
1297
1298 /**
1299  * Sets whether RFC2833 is to be used for sending digits.
1300  *
1301  * @ingroup media_parameters
1302 **/
1303 void linphone_core_set_use_rfc2833_for_dtmf(LinphoneCore *lc,bool_t use_rfc2833)
1304 {
1305         lc->sip_conf.use_rfc2833=use_rfc2833;
1306 }
1307
1308 /**
1309  * Returns the UDP port used by SIP.
1310  *
1311  * Deprecated: use linphone_core_get_sip_transports() instead.
1312  * @ingroup network_parameters
1313 **/
1314 int linphone_core_get_sip_port(LinphoneCore *lc)
1315 {
1316         LCSipTransports *tr=&lc->sip_conf.transports;
1317         return tr->udp_port>0 ? tr->udp_port : tr->tcp_port;
1318 }
1319
1320 static char _ua_name[64]="Linphone";
1321 static char _ua_version[64]=LINPHONE_VERSION;
1322
1323 #ifdef HAVE_EXOSIP_GET_VERSION
1324 extern const char *eXosip_get_version();
1325 #endif
1326
1327 static void apply_user_agent(LinphoneCore *lc){
1328         char ua_string[256];
1329         snprintf(ua_string,sizeof(ua_string)-1,"%s/%s (eXosip2/%s)",_ua_name,_ua_version,
1330 #ifdef HAVE_EXOSIP_GET_VERSION
1331                  eXosip_get_version()
1332 #else
1333                  "unknown"
1334 #endif
1335         );
1336         if (lc->sal) sal_set_user_agent(lc->sal,ua_string);
1337 }
1338
1339 /**
1340  * Sets the user agent string used in SIP messages.
1341  *
1342  * @ingroup misc
1343 **/
1344 void linphone_core_set_user_agent(const char *name, const char *ver){
1345         strncpy(_ua_name,name,sizeof(_ua_name)-1);
1346         strncpy(_ua_version,ver,sizeof(_ua_version));
1347 }
1348
1349 static void transport_error(LinphoneCore *lc, const char* transport, int port){
1350         char *msg=ortp_strdup_printf("Could not start %s transport on port %i, maybe this port is already used.",transport,port);
1351         ms_warning(msg);
1352         if (lc->vtable.display_warning)
1353                 lc->vtable.display_warning(lc,msg);
1354         ms_free(msg);
1355 }
1356
1357 static bool_t transports_unchanged(const LCSipTransports * tr1, const LCSipTransports * tr2){
1358         return
1359                 tr2->udp_port==tr1->udp_port &&
1360                 tr2->tcp_port==tr1->tcp_port &&
1361                 tr2->dtls_port==tr1->dtls_port &&
1362                 tr2->tls_port==tr1->tls_port;
1363 }
1364
1365 static int apply_transports(LinphoneCore *lc){
1366         Sal *sal=lc->sal;
1367         const char *anyaddr;
1368         LCSipTransports *tr=&lc->sip_conf.transports;
1369
1370         if (lc->sip_conf.ipv6_enabled)
1371                 anyaddr="::0";
1372         else
1373                 anyaddr="0.0.0.0";
1374
1375         sal_unlisten_ports (sal);
1376         if (tr->udp_port>0){
1377                 if (sal_listen_port (sal,anyaddr,tr->udp_port,SalTransportDatagram,FALSE)!=0){
1378                         transport_error(lc,"UDP",tr->udp_port);
1379                         return -1;
1380                 }
1381         }
1382         if (tr->tcp_port>0){
1383                 if (sal_listen_port (sal,anyaddr,tr->tcp_port,SalTransportStream,FALSE)!=0){
1384                         transport_error(lc,"TCP",tr->tcp_port);
1385                 }
1386         }
1387         apply_user_agent(lc);
1388         return 0;
1389 }
1390
1391 /**
1392  * Sets the ports to be used for each of transport (UDP or TCP)
1393  *
1394  * A zero value port for a given transport means the transport
1395  * is not used.
1396  *
1397  * @ingroup network_parameters
1398 **/
1399 int linphone_core_set_sip_transports(LinphoneCore *lc, const LCSipTransports * tr){
1400         
1401         if (transports_unchanged(tr,&lc->sip_conf.transports))
1402                 return 0;
1403         memcpy(&lc->sip_conf.transports,tr,sizeof(*tr));
1404         
1405         if (lc->sal==NULL) return 0;
1406         return apply_transports(lc);
1407 }
1408
1409 /**
1410  * Retrieves the ports used for each transport (udp, tcp).
1411  * A zero value port for a given transport means the transport
1412  * is not used.
1413  * @ingroup network_parameters
1414 **/
1415 int linphone_core_get_sip_transports(LinphoneCore *lc, LCSipTransports *tr){
1416         memcpy(tr,&lc->sip_conf.transports,sizeof(*tr));
1417         return 0;
1418 }
1419
1420 /**
1421  * Sets the UDP port to be used by SIP.
1422  *
1423  * Deprecated: use linphone_core_set_sip_transports() instead.
1424  * @ingroup network_parameters
1425 **/
1426 void linphone_core_set_sip_port(LinphoneCore *lc,int port)
1427 {
1428         LCSipTransports tr;
1429         memset(&tr,0,sizeof(tr));
1430         tr.udp_port=port;
1431         linphone_core_set_sip_transports (lc,&tr);
1432 }
1433
1434 /**
1435  * Returns TRUE if IPv6 is enabled.
1436  *
1437  * @ingroup network_parameters
1438  * See linphone_core_enable_ipv6() for more details on how IPv6 is supported in liblinphone.
1439 **/
1440 bool_t linphone_core_ipv6_enabled(LinphoneCore *lc){
1441         return lc->sip_conf.ipv6_enabled;
1442 }
1443
1444 /**
1445  * Turns IPv6 support on or off.
1446  *
1447  * @ingroup network_parameters
1448  *
1449  * @note IPv6 support is exclusive with IPv4 in liblinphone:
1450  * when IPv6 is turned on, IPv4 calls won't be possible anymore.
1451  * By default IPv6 support is off.
1452 **/
1453 void linphone_core_enable_ipv6(LinphoneCore *lc, bool_t val){
1454         if (lc->sip_conf.ipv6_enabled!=val){
1455                 lc->sip_conf.ipv6_enabled=val;
1456                 if (lc->sal){
1457                         /* we need to restart eXosip */
1458                         apply_transports(lc);
1459                 }
1460         }
1461 }
1462
1463
1464 static void monitor_network_state(LinphoneCore *lc, time_t curtime){
1465         static time_t last_check=0;
1466         static bool_t last_status=FALSE;
1467         char result[LINPHONE_IPADDR_SIZE];
1468         bool_t new_status=last_status;
1469
1470         /* only do the network up checking every five seconds */
1471         if (last_check==0 || (curtime-last_check)>=5){
1472                 linphone_core_get_local_ip_for(lc->sip_conf.ipv6_enabled ? AF_INET6 : AF_INET,NULL,result);
1473                 if (strcmp(result,"::1")!=0 && strcmp(result,"127.0.0.1")!=0){
1474                         new_status=TRUE;
1475                 }else new_status=FALSE;
1476                 last_check=curtime;
1477                 if (new_status!=last_status) {
1478                         if (new_status){
1479                                 ms_message("New local ip address is %s",result);
1480                         }
1481                         set_network_reachable(lc,new_status, curtime);
1482                         last_status=new_status;
1483                 }
1484         }
1485 }
1486
1487 static void proxy_update(LinphoneCore *lc){
1488         ms_list_for_each(lc->sip_conf.proxies,(void (*)(void*))&linphone_proxy_config_update);
1489         MSList* list=ms_list_copy(lc->sip_conf.deleted_proxies);
1490         for(;list!=NULL;list=list->next){
1491                 LinphoneProxyConfig* cfg = (LinphoneProxyConfig*) list->data;
1492                 if (ms_time(NULL) - cfg->deletion_date > 5) {
1493                         lc->sip_conf.deleted_proxies =ms_list_remove(lc->sip_conf.deleted_proxies,(void *)cfg);
1494                         ms_message("clearing proxy config for [%s]",linphone_proxy_config_get_addr(cfg));
1495                         linphone_proxy_config_destroy(cfg);
1496                 }
1497         }
1498         ms_list_free(list);
1499 }
1500
1501 static void assign_buddy_info(LinphoneCore *lc, BuddyInfo *info){
1502         LinphoneFriend *lf=linphone_core_get_friend_by_address(lc,info->sip_uri);
1503         if (lf!=NULL){
1504                 lf->info=info;
1505                 ms_message("%s has a BuddyInfo assigned with image %p",info->sip_uri, info->image_data);
1506                 if (lc->vtable.buddy_info_updated)
1507                         lc->vtable.buddy_info_updated(lc,lf);
1508         }else{
1509                 ms_warning("Could not any friend with uri %s",info->sip_uri);
1510         }
1511 }
1512
1513 static void analyze_buddy_lookup_results(LinphoneCore *lc, LinphoneProxyConfig *cfg){
1514         MSList *elem;
1515         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1516         for (elem=lc->bl_reqs;elem!=NULL;elem=ms_list_next(elem)){
1517                 BuddyLookupRequest *req=(BuddyLookupRequest *)elem->data;
1518                 if (req->status==BuddyLookupDone || req->status==BuddyLookupFailure){
1519                         if (req->results!=NULL){
1520                                 BuddyInfo *i=(BuddyInfo*)req->results->data;
1521                                 ms_list_free(req->results);
1522                                 req->results=NULL;
1523                                 assign_buddy_info(lc,i);
1524                         }
1525                         sip_setup_context_buddy_lookup_free(ctx,req);
1526                         elem->data=NULL;
1527                 }
1528         }
1529         /*purge completed requests */
1530         while((elem=ms_list_find(lc->bl_reqs,NULL))!=NULL){
1531                 lc->bl_reqs=ms_list_remove_link(lc->bl_reqs,elem);
1532         }
1533 }
1534
1535 static void linphone_core_grab_buddy_infos(LinphoneCore *lc, LinphoneProxyConfig *cfg){
1536         const MSList *elem;
1537         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1538         for(elem=linphone_core_get_friend_list(lc);elem!=NULL;elem=elem->next){
1539                 LinphoneFriend *lf=(LinphoneFriend*)elem->data;
1540                 if (lf->info==NULL){
1541                         if (linphone_core_lookup_known_proxy(lc,lf->uri)==cfg){
1542                                 if (linphone_address_get_username(lf->uri)!=NULL){
1543                                         BuddyLookupRequest *req;
1544                                         char *tmp=linphone_address_as_string_uri_only(lf->uri);
1545                                         req=sip_setup_context_create_buddy_lookup_request(ctx);
1546                                         buddy_lookup_request_set_key(req,tmp);
1547                                         buddy_lookup_request_set_max_results(req,1);
1548                                         sip_setup_context_buddy_lookup_submit(ctx,req);
1549                                         lc->bl_reqs=ms_list_append(lc->bl_reqs,req);
1550                                         ms_free(tmp);
1551                                 }
1552                         }
1553                 }
1554         }
1555 }
1556
1557 static void linphone_core_do_plugin_tasks(LinphoneCore *lc){
1558         LinphoneProxyConfig *cfg=NULL;
1559         linphone_core_get_default_proxy(lc,&cfg);
1560         if (cfg){
1561                 if (lc->bl_refresh){
1562                         SipSetupContext *ctx=linphone_proxy_config_get_sip_setup_context(cfg);
1563                         if (ctx && (sip_setup_context_get_capabilities(ctx) & SIP_SETUP_CAP_BUDDY_LOOKUP)){
1564                                 linphone_core_grab_buddy_infos(lc,cfg);
1565                                 lc->bl_refresh=FALSE;
1566                         }
1567                 }
1568                 if (lc->bl_reqs) analyze_buddy_lookup_results(lc,cfg);
1569         }
1570 }
1571
1572 /**
1573  * Main loop function. It is crucial that your application call it periodically.
1574  *
1575  * @ingroup initializing
1576  * linphone_core_iterate() performs various backgrounds tasks:
1577  * - receiving of SIP messages
1578  * - handles timers and timeout
1579  * - performs registration to proxies
1580  * - authentication retries
1581  * The application MUST call this function periodically, in its main loop.
1582  * Be careful that this function must be called from the same thread as
1583  * other liblinphone methods. If it is not the case make sure all liblinphone calls are
1584  * serialized with a mutex.
1585 **/
1586 void linphone_core_iterate(LinphoneCore *lc){
1587         MSList *calls;
1588         LinphoneCall *call;
1589         time_t curtime=time(NULL);
1590         int elapsed;
1591         bool_t one_second_elapsed=FALSE;
1592
1593         if (curtime-lc->prevtime>=1){
1594                 lc->prevtime=curtime;
1595                 one_second_elapsed=TRUE;
1596         }
1597
1598         if (lc->ecc!=NULL){
1599                 LinphoneEcCalibratorStatus ecs=ec_calibrator_get_status(lc->ecc);
1600                 if (ecs!=LinphoneEcCalibratorInProgress){
1601                         if (lc->ecc->cb)
1602                                 lc->ecc->cb(lc,ecs,lc->ecc->delay,lc->ecc->cb_data);
1603                         if (ecs==LinphoneEcCalibratorDone){
1604                                 lp_config_set_int(lc->config, "sound", "ec_delay",MAX(lc->ecc->delay-10,0));
1605                         }
1606                         ec_calibrator_destroy(lc->ecc);
1607                         lc->ecc=NULL;
1608                 }
1609         }
1610
1611         if (lc->preview_finished){
1612                 lc->preview_finished=0;
1613                 ring_stop(lc->ringstream);
1614                 lc->ringstream=NULL;
1615                 lc_callback_obj_invoke(&lc->preview_finished_cb,lc);
1616         }
1617
1618         if (lc->ringstream && lc->ringstream_autorelease && lc->dmfs_playing_start_time!=0 
1619             && (curtime-lc->dmfs_playing_start_time)>5){
1620                 ring_stop(lc->ringstream);
1621                 lc->ringstream=NULL;
1622                 lc->dmfs_playing_start_time=0;
1623         }
1624
1625         sal_iterate(lc->sal);
1626         if (lc->msevq) ms_event_queue_pump(lc->msevq);
1627         if (lc->auto_net_state_mon) monitor_network_state(lc,curtime);
1628
1629         proxy_update(lc);
1630
1631         //we have to iterate for each call
1632         calls= lc->calls;
1633         while(calls!= NULL){
1634                 call = (LinphoneCall *)calls->data;
1635                  /* get immediately a reference to next one in case the one
1636                  we are going to examine is destroy and removed during
1637                  linphone_core_start_invite() */
1638                 calls=calls->next;
1639                 if (call->state==LinphoneCallOutgoingInit && (curtime-call->start_time>=2)){
1640                                 /*start the call even if the OPTIONS reply did not arrive*/
1641                                 linphone_core_start_invite(lc,call,NULL);
1642                         }
1643                 if (call->dir==LinphoneCallIncoming && call->state==LinphoneCallOutgoingRinging){
1644                         elapsed=curtime-call->start_time;
1645                         ms_message("incoming call ringing for %i seconds",elapsed);
1646                         if (elapsed>lc->sip_conf.inc_timeout){
1647                                 call->log->status=LinphoneCallMissed;
1648                                 linphone_core_terminate_call(lc,call);
1649                         }
1650                 }
1651         }
1652         call = linphone_core_get_current_call(lc);
1653         if(call)
1654                 linphone_call_background_tasks(call,one_second_elapsed);
1655         if (linphone_core_video_preview_enabled(lc)){
1656                 if (lc->previewstream==NULL && lc->calls==NULL)
1657                         toggle_video_preview(lc,TRUE);
1658 #ifdef VIDEO_ENABLED
1659                 if (lc->previewstream) video_stream_iterate(lc->previewstream);
1660 #endif
1661         }else{
1662                 if (lc->previewstream!=NULL)
1663                         toggle_video_preview(lc,FALSE);
1664         }
1665
1666         linphone_core_run_hooks(lc);
1667         linphone_core_do_plugin_tasks(lc);
1668
1669         if (lc->initial_subscribes_sent==FALSE && lc->netup_time!=0 &&
1670             (curtime-lc->netup_time)>3){
1671                 linphone_core_send_initial_subscribes(lc);
1672                 lc->initial_subscribes_sent=TRUE;
1673         }
1674
1675         if (one_second_elapsed && lp_config_needs_commit(lc->config)){
1676                 lp_config_sync(lc->config);
1677         }
1678 }
1679
1680 /**
1681  * Interpret a call destination as supplied by the user, and returns a fully qualified
1682  * LinphoneAddress.
1683  *
1684  * A sip address should look like DisplayName <sip:username@domain:port> .
1685  * Basically this function performs the following tasks
1686  * - if a phone number is entered, prepend country prefix of the default proxy
1687  *   configuration, eventually escape the '+' by 00.
1688  * - if no domain part is supplied, append the domain name of the default proxy
1689  * - if no sip: is present, prepend it
1690  * 
1691  * The result is a syntaxically correct SIP address.
1692 **/
1693
1694 LinphoneAddress * linphone_core_interpret_url(LinphoneCore *lc, const char *url){
1695         enum_lookup_res_t *enumres=NULL;
1696         char *enum_domain=NULL;
1697         LinphoneProxyConfig *proxy=lc->default_proxy;;
1698         char *tmpurl;
1699         LinphoneAddress *uri;
1700         
1701         if (is_enum(url,&enum_domain)){
1702                 if (lc->vtable.display_status!=NULL)
1703                         lc->vtable.display_status(lc,_("Looking for telephone number destination..."));
1704                 if (enum_lookup(enum_domain,&enumres)<0){
1705                         if (lc->vtable.display_status!=NULL)
1706                                 lc->vtable.display_status(lc,_("Could not resolve this number."));
1707                         ms_free(enum_domain);
1708                         return NULL;
1709                 }
1710                 ms_free(enum_domain);
1711                 tmpurl=enumres->sip_address[0];
1712                 uri=linphone_address_new(tmpurl);
1713                 enum_lookup_res_free(enumres);
1714                 return uri;
1715         }
1716         /* check if we have a "sip:" */
1717         if (strstr(url,"sip:")==NULL){
1718                 /* this doesn't look like a true sip uri */
1719                 if (strchr(url,'@')!=NULL){
1720                         /* seems like sip: is missing !*/
1721                         tmpurl=ms_strdup_printf("sip:%s",url);
1722                         uri=linphone_address_new(tmpurl);
1723                         ms_free(tmpurl);
1724                         if (uri){
1725                                 return uri;
1726                         }
1727                 }
1728                 
1729                 if (proxy!=NULL){
1730                         /* append the proxy domain suffix */
1731                         const char *identity=linphone_proxy_config_get_identity(proxy);
1732                         char normalized_username[128];
1733                         uri=linphone_address_new(identity);
1734                         if (uri==NULL){
1735                                 return NULL;
1736                         }
1737                         linphone_address_set_display_name(uri,NULL);
1738                         linphone_proxy_config_normalize_number(proxy,url,normalized_username,
1739                                                                 sizeof(normalized_username));
1740                         linphone_address_set_username(uri,normalized_username);
1741                         return uri;
1742                 }else return NULL;
1743         }
1744         uri=linphone_address_new(url);
1745         if (uri!=NULL){
1746                 return uri;
1747         }
1748         /* else we could not do anything with url given by user, so display an error */
1749         if (lc->vtable.display_warning!=NULL){
1750                 lc->vtable.display_warning(lc,_("Could not parse given sip address. A sip url usually looks like sip:user@domain"));
1751         }
1752         return NULL;
1753 }
1754
1755 /**
1756  * Returns the default identity SIP address.
1757  *
1758  * @ingroup proxies
1759  * This is an helper function:
1760  *
1761  * If no default proxy is set, this will return the primary contact (
1762  * see linphone_core_get_primary_contact() ). If a default proxy is set
1763  * it returns the registered identity on the proxy.
1764 **/
1765 const char * linphone_core_get_identity(LinphoneCore *lc){
1766         LinphoneProxyConfig *proxy=NULL;
1767         const char *from;
1768         linphone_core_get_default_proxy(lc,&proxy);
1769         if (proxy!=NULL) {
1770                 from=linphone_proxy_config_get_identity(proxy);
1771         }else from=linphone_core_get_primary_contact(lc);
1772         return from;
1773 }
1774
1775 const char * linphone_core_get_route(LinphoneCore *lc){
1776         LinphoneProxyConfig *proxy=NULL;
1777         const char *route=NULL;
1778         linphone_core_get_default_proxy(lc,&proxy);
1779         if (proxy!=NULL) {
1780                 route=linphone_proxy_config_get_route(proxy);
1781         }
1782         return route;
1783 }
1784
1785 void linphone_core_start_refered_call(LinphoneCore *lc, LinphoneCall *call){
1786         if (call->refer_pending){
1787                 LinphoneCallParams *cp=linphone_core_create_default_call_parameters(lc);
1788                 cp->referer=call;
1789                 ms_message("Starting new call to refered address %s",call->refer_to);
1790                 call->refer_pending=FALSE;
1791                 linphone_core_invite_with_params(lc,call->refer_to,cp);
1792                 linphone_call_params_destroy(cp);
1793         }
1794 }
1795
1796 LinphoneProxyConfig * linphone_core_lookup_known_proxy(LinphoneCore *lc, const LinphoneAddress *uri){
1797         const MSList *elem;
1798         LinphoneProxyConfig *found_cfg=NULL;
1799         for (elem=linphone_core_get_proxy_config_list(lc);elem!=NULL;elem=elem->next){
1800                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
1801                 const char *domain=linphone_proxy_config_get_domain(cfg);
1802                 if (domain!=NULL && strcmp(domain,linphone_address_get_domain(uri))==0){
1803                         found_cfg=cfg;
1804                         break;
1805                 }
1806         }
1807         return found_cfg;
1808 }
1809
1810 const char *linphone_core_find_best_identity(LinphoneCore *lc, const LinphoneAddress *to, const char **route){
1811         LinphoneProxyConfig *cfg=linphone_core_lookup_known_proxy(lc,to);
1812         if (cfg==NULL)
1813                 linphone_core_get_default_proxy (lc,&cfg);
1814         if (cfg!=NULL){
1815                 if (route) *route=linphone_proxy_config_get_route(cfg);
1816                 return linphone_proxy_config_get_identity (cfg);
1817         }
1818         return linphone_core_get_primary_contact (lc);
1819 }
1820
1821 static char *get_fixed_contact(LinphoneCore *lc, LinphoneCall *call , LinphoneProxyConfig *dest_proxy){
1822         LinphoneAddress *ctt;
1823         const char *localip=call->localip;
1824
1825         /* first use user's supplied ip address if asked*/
1826         if (linphone_core_get_firewall_policy(lc)==LinphonePolicyUseNatAddress){
1827                 ctt=linphone_core_get_primary_contact_parsed(lc);
1828                 return ms_strdup_printf("sip:%s@%s",linphone_address_get_username(ctt),
1829                         linphone_core_get_nat_address_resolved(lc));
1830         }
1831
1832         /* if already choosed, don't change it */
1833         if (call->op && sal_op_get_contact(call->op)!=NULL){
1834                 return NULL;
1835         }
1836         /* if the ping OPTIONS request succeeded use the contact guessed from the
1837          received, rport*/
1838         if (call->ping_op){
1839                 const char *guessed=sal_op_get_contact(call->ping_op);
1840                 if (guessed){
1841                         ms_message("Contact has been fixed using OPTIONS to %s",guessed);
1842                         return ms_strdup(guessed);
1843                 }
1844         }
1845
1846         /*if using a proxy, use the contact address as guessed with the REGISTERs*/
1847         if (dest_proxy && dest_proxy->op){
1848                 const char *fixed_contact=sal_op_get_contact(dest_proxy->op);
1849                 if (fixed_contact) {
1850                         ms_message("Contact has been fixed using proxy to %s",fixed_contact);
1851                         return ms_strdup(fixed_contact);
1852                 }
1853         }
1854         
1855         ctt=linphone_core_get_primary_contact_parsed(lc);
1856         
1857         if (ctt!=NULL){
1858                 char *ret;
1859                 /*otherwise use supllied localip*/
1860                 linphone_address_set_domain(ctt,localip);
1861                 linphone_address_set_port_int(ctt,linphone_core_get_sip_port(lc));
1862                 ret=linphone_address_as_string_uri_only(ctt);
1863                 linphone_address_destroy(ctt);
1864                 ms_message("Contact has been fixed using local ip to %s",ret);
1865                 return ret;
1866         }
1867         return NULL;
1868 }
1869
1870 int linphone_core_start_invite(LinphoneCore *lc, LinphoneCall *call, LinphoneProxyConfig *dest_proxy){
1871         int err;
1872         char *contact;
1873         char *real_url,*barmsg;
1874         char *from;
1875         
1876         /*try to be best-effort in giving real local or routable contact address */
1877         contact=get_fixed_contact(lc,call,dest_proxy);
1878         if (contact){
1879                 sal_op_set_contact(call->op, contact);
1880                 ms_free(contact);
1881         }
1882         
1883         //TODO : should probably not be done here
1884         linphone_call_init_media_streams(call);
1885         if (!lc->sip_conf.sdp_200_ack){ 
1886                 call->media_pending=TRUE;
1887                 sal_call_set_local_media_description(call->op,call->localdesc);
1888         }
1889         real_url=linphone_address_as_string(call->log->to);
1890         from=linphone_address_as_string(call->log->from);
1891         err=sal_call(call->op,from,real_url);
1892
1893         if (lc->sip_conf.sdp_200_ack){
1894                 call->media_pending=TRUE;
1895                 sal_call_set_local_media_description(call->op,call->localdesc);
1896         }
1897         barmsg=ortp_strdup_printf("%s %s", _("Contacting"), real_url);
1898         if (lc->vtable.display_status!=NULL)
1899                 lc->vtable.display_status(lc,barmsg);
1900         ms_free(barmsg);
1901         
1902         if (err<0){
1903                 if (lc->vtable.display_status!=NULL)
1904                         lc->vtable.display_status(lc,_("Could not call"));
1905                 linphone_call_stop_media_streams(call);
1906                 linphone_call_set_state(call,LinphoneCallError,"Call failed");
1907         }else {
1908                 linphone_call_set_state(call,LinphoneCallOutgoingProgress,"Outgoing call in progress");
1909         }
1910         ms_free(real_url);
1911         ms_free(from);
1912         return err;
1913 }
1914
1915 /**
1916  * Initiates an outgoing call
1917  *
1918  * @ingroup call_control
1919  * @param lc the LinphoneCore object
1920  * @param url the destination of the call (sip address, or phone number).
1921  *
1922  * The application doesn't own a reference to the returned LinphoneCall object.
1923  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
1924  *
1925  * @return a LinphoneCall object or NULL in case of failure
1926 **/
1927 LinphoneCall * linphone_core_invite(LinphoneCore *lc, const char *url){
1928         LinphoneCall *call;
1929         LinphoneCallParams *p=linphone_core_create_default_call_parameters (lc);
1930         call=linphone_core_invite_with_params(lc,url,p);
1931         linphone_call_params_destroy(p);
1932         return call;
1933 }
1934
1935
1936 /**
1937  * Initiates an outgoing call according to supplied call parameters
1938  *
1939  * @ingroup call_control
1940  * @param lc the LinphoneCore object
1941  * @param url the destination of the call (sip address, or phone number).
1942  * @param p call parameters
1943  *
1944  * The application doesn't own a reference to the returned LinphoneCall object.
1945  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
1946  *
1947  * @return a LinphoneCall object or NULL in case of failure
1948 **/
1949 LinphoneCall * linphone_core_invite_with_params(LinphoneCore *lc, const char *url, const LinphoneCallParams *p){
1950         LinphoneAddress *addr=linphone_core_interpret_url(lc,url);
1951         if (addr){
1952                 LinphoneCall *call;
1953                 call=linphone_core_invite_address_with_params(lc,addr,p);
1954                 linphone_address_destroy(addr);
1955                 return call;
1956         }
1957         return NULL;
1958 }
1959
1960 /**
1961  * Initiates an outgoing call given a destination LinphoneAddress
1962  *
1963  * @ingroup call_control
1964  * @param lc the LinphoneCore object
1965  * @param addr the destination of the call (sip address).
1966  * 
1967  * The LinphoneAddress can be constructed directly using linphone_address_new(), or
1968  * created by linphone_core_interpret_url().
1969  * The application doesn't own a reference to the returned LinphoneCall object.
1970  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
1971  *
1972  * @return a LinphoneCall object or NULL in case of failure
1973 **/
1974 LinphoneCall * linphone_core_invite_address(LinphoneCore *lc, const LinphoneAddress *addr){
1975         LinphoneCall *call;
1976         LinphoneCallParams *p=linphone_core_create_default_call_parameters (lc);
1977         call=linphone_core_invite_address_with_params (lc,addr,p);
1978         linphone_call_params_destroy(p);
1979         return call;
1980 }
1981
1982
1983 /**
1984  * Initiates an outgoing call given a destination LinphoneAddress
1985  *
1986  * @ingroup call_control
1987  * @param lc the LinphoneCore object
1988  * @param addr the destination of the call (sip address).
1989         @param params call parameters
1990  * 
1991  * The LinphoneAddress can be constructed directly using linphone_address_new(), or
1992  * created by linphone_core_interpret_url().
1993  * The application doesn't own a reference to the returned LinphoneCall object.
1994  * Use linphone_call_ref() to safely keep the LinphoneCall pointer valid within your application.
1995  *
1996  * @return a LinphoneCall object or NULL in case of failure
1997 **/
1998 LinphoneCall * linphone_core_invite_address_with_params(LinphoneCore *lc, const LinphoneAddress *addr, const LinphoneCallParams *params)
1999 {
2000         int err=0;
2001         const char *route=NULL;
2002         const char *from=NULL;
2003         LinphoneProxyConfig *proxy=NULL;
2004         LinphoneAddress *parsed_url2=NULL;
2005         char *real_url=NULL;
2006         LinphoneProxyConfig *dest_proxy=NULL;
2007         LinphoneCall *call;
2008         
2009         if (linphone_core_in_call(lc)){
2010                 if (lc->vtable.display_warning)
2011                         lc->vtable.display_warning(lc,_("Sorry, you have to pause or stop the current call first !"));
2012                 return NULL;
2013         }
2014         if(!linphone_core_can_we_add_call(lc)){
2015                 if (lc->vtable.display_warning)
2016                         lc->vtable.display_warning(lc,_("Sorry, we have reached the maximum number of simultaneous calls"));
2017                 return NULL;
2018         }
2019         linphone_core_get_default_proxy(lc,&proxy);
2020         route=linphone_core_get_route(lc);
2021         
2022         real_url=linphone_address_as_string(addr);
2023         dest_proxy=linphone_core_lookup_known_proxy(lc,addr);
2024
2025         if (proxy!=dest_proxy && dest_proxy!=NULL) {
2026                 ms_message("Overriding default proxy setting for this call:");
2027                 ms_message("The used identity will be %s",linphone_proxy_config_get_identity(dest_proxy));
2028         }
2029
2030         if (dest_proxy!=NULL)
2031                 from=linphone_proxy_config_get_identity(dest_proxy);
2032         else if (proxy!=NULL)
2033                 from=linphone_proxy_config_get_identity(proxy);
2034
2035         /* if no proxy or no identity defined for this proxy, default to primary contact*/
2036         if (from==NULL) from=linphone_core_get_primary_contact(lc);
2037
2038         parsed_url2=linphone_address_new(from);
2039
2040         call=linphone_call_new_outgoing(lc,parsed_url2,linphone_address_clone(addr),params);
2041         sal_op_set_route(call->op,route);
2042         
2043         if(linphone_core_add_call(lc,call)!= 0)
2044         {
2045                 ms_warning("we had a problem in adding the call into the invite ... weird");
2046                 linphone_call_unref(call);
2047                 return NULL;
2048         }
2049         /* this call becomes now the current one*/
2050         lc->current_call=call;
2051         linphone_call_set_state (call,LinphoneCallOutgoingInit,"Starting outgoing call");
2052         if (dest_proxy!=NULL || lc->sip_conf.ping_with_options==FALSE){
2053                 err=linphone_core_start_invite(lc,call,dest_proxy);
2054         }else{
2055                 /*defer the start of the call after the OPTIONS ping*/
2056                 call->ping_op=sal_op_new(lc->sal);
2057                 sal_ping(call->ping_op,from,real_url);
2058                 sal_op_set_user_pointer(call->ping_op,call);
2059                 call->start_time=time(NULL);
2060         }
2061         
2062         if (real_url!=NULL) ms_free(real_url);
2063         return call;
2064 }
2065
2066 /**
2067  * Performs a simple call transfer to the specified destination.
2068  *
2069  * The remote endpoint is expected to issue a new call to the specified destination.
2070  * The current call remains active and thus can be later paused or terminated.
2071 **/
2072 int linphone_core_transfer_call(LinphoneCore *lc, LinphoneCall *call, const char *url)
2073 {
2074         char *real_url=NULL;
2075         LinphoneAddress *real_parsed_url=linphone_core_interpret_url(lc,url);
2076
2077         if (!real_parsed_url){
2078                 /* bad url */
2079                 return -1;
2080         }
2081         if (call==NULL){
2082                 ms_warning("No established call to refer.");
2083                 return -1;
2084         }
2085         //lc->call=NULL; //Do not do that you will lose the call afterward . . .
2086         real_url=linphone_address_as_string (real_parsed_url);
2087         sal_call_refer(call->op,real_url);
2088         ms_free(real_url);
2089         linphone_address_destroy(real_parsed_url);
2090         return 0;
2091 }
2092
2093 /**
2094  * Transfer a call to destination of another running call. This is used for "attended transfer" scenarios.
2095  * @param lc linphone core object
2096  * @param call a running call you want to transfer
2097  * @param dest a running call whose remote person will receive the transfer
2098  *
2099  * The transfered call is supposed to be in paused state, so that it is able to accept the transfer immediately.
2100  * The destination call is a call previously established to introduce the transfered person.
2101  * This method will send a transfer request to the transfered person. The phone of the transfered is then
2102  * expected to automatically call to the destination of the transfer. The receiver of the transfer will then automatically
2103  * close the call with us (the 'dest' call).
2104 **/
2105 int linphone_core_transfer_call_to_another(LinphoneCore *lc, LinphoneCall *call, LinphoneCall *dest){
2106         return sal_call_refer_with_replaces (call->op,dest->op);
2107 }
2108
2109 bool_t linphone_core_inc_invite_pending(LinphoneCore*lc){
2110         LinphoneCall *call = linphone_core_get_current_call(lc);
2111         if(call != NULL)
2112         {
2113                 if(call->dir==LinphoneCallIncoming
2114                         && (call->state == LinphoneCallIncomingReceived || call->state ==  LinphoneCallIncomingEarlyMedia))
2115                         return TRUE;
2116         }
2117         return FALSE;
2118 }
2119
2120 /**
2121  * Updates a running call according to supplied call parameters or parameters changed in the LinphoneCore.
2122  *
2123  * In this version this is limited to the following use cases:
2124  * - setting up/down the video stream according to the video parameter of the LinphoneCallParams (see linphone_call_params_enable_video() ).
2125  * - changing the size of the transmitted video after calling linphone_core_set_preferred_video_size()
2126  *
2127  * In case no changes are requested through the LinphoneCallParams argument, then this argument can be ommitted and set to NULL.
2128  *
2129  * @return 0 if successful, -1 otherwise.
2130 **/
2131 int linphone_core_update_call(LinphoneCore *lc, LinphoneCall *call, const LinphoneCallParams *params){
2132         int err=0;
2133         if (params!=NULL){
2134                 call->params=*params;
2135                 update_local_media_description(lc,call,&call->localdesc);
2136                 call->camera_active=params->has_video;
2137                 if (lc->vtable.display_status)
2138                         lc->vtable.display_status(lc,_("Modifying call parameters..."));
2139                 sal_call_set_local_media_description (call->op,call->localdesc);
2140                 err=sal_call_update(call->op,"Media parameters update");
2141         }else{
2142 #ifdef VIDEO_ENABLED
2143                 if (call->videostream!=NULL){
2144                         video_stream_set_sent_video_size(call->videostream,linphone_core_get_preferred_video_size(lc));
2145                         video_stream_update_video_params (call->videostream);
2146                 }
2147 #endif
2148         }
2149
2150         return err;
2151 }
2152
2153
2154 /**
2155  * Accept an incoming call.
2156  *
2157  * @ingroup call_control
2158  * Basically the application is notified of incoming calls within the
2159  * call_state_changed callback of the #LinphoneCoreVTable structure, where it will receive
2160  * a LinphoneCallIncoming event with the associated LinphoneCall object.
2161  * The application can later accept the call using
2162  * this method.
2163  * @param lc the LinphoneCore object
2164  * @param call the LinphoneCall object representing the call to be answered.
2165  * 
2166 **/
2167 int linphone_core_accept_call(LinphoneCore *lc, LinphoneCall *call)
2168 {
2169         LinphoneProxyConfig *cfg=NULL,*dest_proxy=NULL;
2170         const char *contact=NULL;
2171         SalOp *replaced;
2172         SalMediaDescription *new_md;
2173         
2174         if (call==NULL){
2175                 //if just one call is present answer the only one ...
2176                 if(linphone_core_get_calls_nb (lc) != 1)
2177                         return -1;
2178                 else
2179                         call = (LinphoneCall*)linphone_core_get_calls(lc)->data;
2180         }
2181
2182         if (call->state==LinphoneCallConnected){
2183                 /*call already accepted*/
2184                 return -1;
2185         }
2186         
2187         /* check if this call is supposed to replace an already running one*/
2188         replaced=sal_call_get_replaces(call->op);
2189         if (replaced){
2190                 LinphoneCall *rc=(LinphoneCall*)sal_op_get_user_pointer (replaced);
2191                 if (rc){
2192                         ms_message("Call %p replaces call %p. This last one is going to be terminated automatically.",
2193                                    call,rc);
2194                         linphone_core_terminate_call (lc,rc);
2195                 }
2196         }
2197
2198         if (lc->current_call!=NULL && lc->current_call!=call){
2199                 ms_warning("Cannot accept this call, there is already one running.");
2200                 return -1;
2201         }
2202         
2203         /*can accept a new call only if others are on hold */
2204         {
2205                 MSList *elem;
2206                 for(elem=lc->calls;elem!=NULL;elem=elem->next){
2207                         LinphoneCall *c=(LinphoneCall*)elem->data;
2208                         if (c!=call && (c->state!=LinphoneCallPaused && c->state!=LinphoneCallPausing)){
2209                                 ms_warning("Cannot accept this call as another one is running, pause it before.");
2210                                 return -1;
2211                         }
2212                 }
2213         }
2214
2215         /*stop ringing */
2216         if (lc->ringstream!=NULL) {
2217                 ms_message("stop ringing");
2218                 ring_stop(lc->ringstream);
2219                 ms_message("ring stopped");
2220                 lc->ringstream=NULL;
2221         }
2222         
2223         linphone_core_get_default_proxy(lc,&cfg);
2224         dest_proxy=cfg;
2225         dest_proxy=linphone_core_lookup_known_proxy(lc,call->log->to);
2226
2227         if (cfg!=dest_proxy && dest_proxy!=NULL) {
2228                 ms_message("Overriding default proxy setting for this call:");
2229                 ms_message("The used identity will be %s",linphone_proxy_config_get_identity(dest_proxy));
2230         }
2231         /*try to be best-effort in giving real local or routable contact address*/
2232         contact=get_fixed_contact(lc,call,dest_proxy);
2233         if (contact)
2234                 sal_op_set_contact(call->op,contact);
2235
2236         if (call->audiostream==NULL)
2237                 linphone_call_init_media_streams(call);
2238         
2239         sal_call_accept(call->op);
2240         if (lc->vtable.display_status!=NULL)
2241                 lc->vtable.display_status(lc,_("Connected."));
2242         lc->current_call=call;
2243         linphone_call_set_state(call,LinphoneCallConnected,"Connected");
2244         new_md=sal_call_get_final_media_description(call->op);
2245         linphone_core_update_streams(lc, call, new_md);
2246         if (new_md){
2247                 linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
2248         }else call->media_pending=TRUE;
2249         
2250         ms_message("call answered.");
2251         return 0;
2252 }
2253
2254 int linphone_core_abort_call(LinphoneCore *lc, LinphoneCall *call, const char *error){
2255         sal_call_terminate(call->op);
2256
2257         /*stop ringing*/
2258         if (lc->ringstream!=NULL) {
2259                 ring_stop(lc->ringstream);
2260                 lc->ringstream=NULL;
2261         }
2262         linphone_call_stop_media_streams(call);
2263         if (lc->vtable.display_status!=NULL)
2264                 lc->vtable.display_status(lc,_("Call aborted") );
2265         linphone_call_set_state(call,LinphoneCallError,error);
2266         return 0;
2267 }
2268
2269 static void terminate_call(LinphoneCore *lc, LinphoneCall *call){
2270         if (call->state==LinphoneCallIncomingReceived){
2271                 call->reason=LinphoneReasonDeclined;
2272         }
2273         /*stop ringing*/
2274         if (lc->ringstream!=NULL) {
2275                 ring_stop(lc->ringstream);
2276                 lc->ringstream=NULL;
2277         }
2278         linphone_call_stop_media_streams(call);
2279         if (lc->vtable.display_status!=NULL)
2280                 lc->vtable.display_status(lc,_("Call ended") );
2281 }
2282
2283 int linphone_core_redirect_call(LinphoneCore *lc, LinphoneCall *call, const char *redirect_uri){
2284         if (call->state==LinphoneCallIncomingReceived){
2285                 sal_call_decline(call->op,SalReasonRedirect,redirect_uri);
2286                 call->reason=LinphoneReasonDeclined;
2287                 terminate_call(lc,call);
2288                 linphone_call_set_state(call,LinphoneCallEnd,"Call terminated");
2289         }else{
2290                 ms_error("Bad state for call redirection.");
2291                 return -1;
2292     }
2293         return 0;
2294 }
2295
2296
2297 /**
2298  * Terminates a call.
2299  *
2300  * @ingroup call_control
2301  * @param lc the LinphoneCore
2302  * @param the_call the LinphoneCall object representing the call to be terminated.
2303 **/
2304 int linphone_core_terminate_call(LinphoneCore *lc, LinphoneCall *the_call)
2305 {
2306         LinphoneCall *call;
2307         if (the_call == NULL){
2308                 call = linphone_core_get_current_call(lc);
2309                 if (ms_list_size(lc->calls)==1){
2310                         call=(LinphoneCall*)lc->calls->data;
2311                 }else{
2312                         ms_warning("No unique call to terminate !");
2313                         return -1;
2314                 }
2315         }
2316         else
2317         {
2318                 call = the_call;
2319         }
2320         sal_call_terminate(call->op);
2321         terminate_call(lc,call);
2322         
2323         linphone_call_set_state(call,LinphoneCallEnd,"Call terminated");
2324         return 0;
2325 }
2326
2327 /**
2328  * Terminates all the calls.
2329  *
2330  * @ingroup call_control
2331  * @param lc The LinphoneCore
2332 **/
2333 int linphone_core_terminate_all_calls(LinphoneCore *lc){
2334         while(lc->calls)
2335         {
2336                 LinphoneCall *the_call = lc->calls->data;
2337                 linphone_core_terminate_call(lc,the_call);
2338         }
2339         ms_list_free(lc->calls);
2340         return -1;
2341 }
2342
2343 /**
2344  * Returns the current list of calls.
2345  *
2346  * Note that this list is read-only and might be changed by the core after a function call to linphone_core_iterate().
2347  * Similarly the LinphoneCall objects inside it might be destroyed without prior notice.
2348  * To hold references to LinphoneCall object into your program, you must use linphone_call_ref().
2349  *
2350  * @ingroup call_control
2351 **/
2352 const MSList *linphone_core_get_calls(LinphoneCore *lc)
2353 {
2354         return lc->calls;
2355 }
2356
2357 /**
2358  * Returns TRUE if there is a call running.
2359  *
2360  * @ingroup call_control
2361 **/
2362 bool_t linphone_core_in_call(const LinphoneCore *lc){
2363         return linphone_core_get_current_call((LinphoneCore *)lc)!=NULL;
2364 }
2365
2366 /**
2367  * Returns The _LinphoneCall struct of the current call if one is in call
2368  *
2369  * @ingroup call_control
2370 **/
2371 LinphoneCall *linphone_core_get_current_call(const LinphoneCore *lc)
2372 {
2373         return lc->current_call;
2374 }
2375
2376 /**
2377  * Pauses the call. If a music file has been setup using linphone_core_set_play_file(),
2378  * this file will be played to the remote user.
2379  *
2380  * @ingroup call_control
2381 **/
2382 int linphone_core_pause_call(LinphoneCore *lc, LinphoneCall *the_call)
2383 {
2384         LinphoneCall *call = the_call;
2385         const char *subject=NULL;
2386
2387         if (call->state!=LinphoneCallStreamsRunning && call->state!=LinphoneCallPausedByRemote){
2388                 ms_warning("Cannot pause this call, it is not active.");
2389                 return -1;
2390         }
2391         if (sal_media_description_has_dir(call->resultdesc,SalStreamSendRecv)){
2392                 sal_media_description_set_dir(call->localdesc,SalStreamSendOnly);
2393                 subject="Call on hold";
2394         }else if (sal_media_description_has_dir(call->resultdesc,SalStreamRecvOnly)){
2395                 sal_media_description_set_dir(call->localdesc,SalStreamSendOnly);
2396                 subject="Call on hold for me too";
2397         }else{
2398                 ms_error("No reason to pause this call, it is already paused or inactive.");
2399                 return -1;
2400         }
2401         if (sal_call_update(call->op,subject) != 0)
2402         {
2403                 if (lc->vtable.display_warning)
2404                         lc->vtable.display_warning(lc,_("Could not pause the call"));
2405         }
2406         linphone_call_set_state(call,LinphoneCallPausing,"Pausing call");
2407         if (lc->vtable.display_status)
2408                 lc->vtable.display_status(lc,_("Pausing the current call..."));
2409         lc->current_call=NULL;
2410         if (call->audiostream || call->videostream)
2411                 linphone_call_stop_media_streams (call);
2412         return 0;
2413 }
2414
2415 /**
2416  * Pause all currently running calls.
2417 **/
2418 int linphone_core_pause_all_calls(LinphoneCore *lc){
2419         const MSList *elem;
2420         for(elem=lc->calls;elem!=NULL;elem=elem->next){
2421                 LinphoneCall *call=(LinphoneCall *)elem->data;
2422                 LinphoneCallState cs=linphone_call_get_state(call);
2423                 if (cs==LinphoneCallStreamsRunning || cs==LinphoneCallPausedByRemote){
2424                         linphone_core_pause_call(lc,call);
2425                 }
2426         }
2427         return 0;
2428 }
2429
2430 /**
2431  * Resumes the call.
2432  *
2433  * @ingroup call_control
2434 **/
2435 int linphone_core_resume_call(LinphoneCore *lc, LinphoneCall *the_call)
2436 {
2437         char temp[255]={0};
2438         LinphoneCall *call = the_call;
2439         
2440         if(call->state!=LinphoneCallPaused ){
2441                 ms_warning("we cannot resume a call that has not been established and paused before");
2442                 return -1;
2443         }
2444         if(linphone_core_get_current_call(lc) != NULL){
2445                 ms_warning("There is already a call in process, pause or stop it first.");
2446                 if (lc->vtable.display_warning)
2447                         lc->vtable.display_warning(lc,_("There is already a call in process, pause or stop it first."));
2448                 return -1;
2449         }
2450         ms_message("Resuming call %p",call);
2451         sal_media_description_set_dir(call->localdesc,SalStreamSendRecv);
2452         if(sal_call_update(call->op,"Call resuming") != 0){
2453                 return -1;
2454         }
2455         linphone_call_set_state (call,LinphoneCallResuming,"Resuming");
2456         snprintf(temp,sizeof(temp)-1,"Resuming the call with %s",linphone_call_get_remote_address_as_string(call));
2457         if (lc->vtable.display_status) 
2458                 lc->vtable.display_status(lc,temp);
2459         return 0;
2460 }
2461
2462 static int remote_address_compare(LinphoneCall *call, const LinphoneAddress *raddr){
2463         const LinphoneAddress *addr=linphone_call_get_remote_address (call);
2464         return !linphone_address_weak_equal (addr,raddr);
2465 }
2466
2467 /**
2468  * Get the call with the remote_address specified
2469  * @param lc
2470  * @param remote_address
2471  * @return the LinphoneCall of the call if found
2472  */
2473 LinphoneCall *linphone_core_get_call_by_remote_address(LinphoneCore *lc, const char *remote_address){
2474         LinphoneAddress *raddr=linphone_address_new(remote_address);
2475         MSList *elem=ms_list_find_custom(lc->calls,(int (*)(const void*,const void *))remote_address_compare,raddr);
2476         if (elem) return (LinphoneCall*) elem->data;
2477         return NULL;
2478 }
2479
2480 int linphone_core_send_publish(LinphoneCore *lc,
2481                                LinphoneOnlineStatus presence_mode)
2482 {
2483         const MSList *elem;
2484         for (elem=linphone_core_get_proxy_config_list(lc);elem!=NULL;elem=ms_list_next(elem)){
2485                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
2486                 if (cfg->publish) linphone_proxy_config_send_publish(cfg,presence_mode);
2487         }
2488         return 0;
2489 }
2490
2491 /**
2492  * Set the incoming call timeout in seconds.
2493  *
2494  * @ingroup call_control
2495  * If an incoming call isn't answered for this timeout period, it is 
2496  * automatically declined.
2497 **/
2498 void linphone_core_set_inc_timeout(LinphoneCore *lc, int seconds){
2499         lc->sip_conf.inc_timeout=seconds;
2500 }
2501
2502 /**
2503  * Returns the incoming call timeout
2504  *
2505  * @ingroup call_control
2506  * See linphone_core_set_inc_timeout() for details.
2507 **/
2508 int linphone_core_get_inc_timeout(LinphoneCore *lc){
2509         return lc->sip_conf.inc_timeout;
2510 }
2511
2512 void linphone_core_set_presence_info(LinphoneCore *lc,int minutes_away,
2513                                                                                                         const char *contact,
2514                                                                                                         LinphoneOnlineStatus presence_mode)
2515 {
2516         if (minutes_away>0) lc->minutes_away=minutes_away;
2517         
2518         if (lc->alt_contact!=NULL) {
2519                 ms_free(lc->alt_contact);
2520                 lc->alt_contact=NULL;
2521         }
2522         if (contact) lc->alt_contact=ms_strdup(contact);
2523         if (lc->presence_mode!=presence_mode){
2524                 linphone_core_notify_all_friends(lc,presence_mode);
2525                 /*
2526                    Improve the use of all LINPHONE_STATUS available.
2527                    !TODO Do not mix "presence status" with "answer status code"..
2528                    Use correct parameter to follow sip_if_match/sip_etag.
2529                  */
2530                 linphone_core_send_publish(lc,presence_mode);
2531         }
2532         lc->presence_mode=presence_mode;
2533 }
2534
2535 LinphoneOnlineStatus linphone_core_get_presence_info(const LinphoneCore *lc){
2536         return lc->presence_mode;
2537 }
2538
2539 /**
2540  * Get playback sound level in 0-100 scale.
2541  *
2542  * @ingroup media_parameters
2543 **/
2544 int linphone_core_get_play_level(LinphoneCore *lc)
2545 {
2546         return lc->sound_conf.play_lev;
2547 }
2548
2549 /**
2550  * Get ring sound level in 0-100 scale
2551  *
2552  * @ingroup media_parameters
2553 **/
2554 int linphone_core_get_ring_level(LinphoneCore *lc)
2555 {
2556         return lc->sound_conf.ring_lev;
2557 }
2558
2559 /**
2560  * Get sound capture level in 0-100 scale
2561  *
2562  * @ingroup media_parameters
2563 **/
2564 int linphone_core_get_rec_level(LinphoneCore *lc){
2565         return lc->sound_conf.rec_lev;
2566 }
2567
2568 /**
2569  * Set sound ring level in 0-100 scale
2570  *
2571  * @ingroup media_parameters
2572 **/
2573 void linphone_core_set_ring_level(LinphoneCore *lc, int level){
2574         MSSndCard *sndcard;
2575         lc->sound_conf.ring_lev=level;
2576         sndcard=lc->sound_conf.ring_sndcard;
2577         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_PLAYBACK,level);
2578 }
2579
2580 /**
2581  * Allow to control play level before entering sound card:  gain in db
2582  *
2583  * @ingroup media_parameters
2584 **/
2585 void linphone_core_set_playback_gain_db (LinphoneCore *lc, float gaindb){
2586         float gain=gaindb;
2587         LinphoneCall *call=linphone_core_get_current_call (lc);
2588         AudioStream *st;
2589
2590         lc->sound_conf.soft_play_lev=gaindb;
2591
2592         if (call==NULL || (st=call->audiostream)==NULL){
2593                 ms_message("linphone_core_set_playback_gain_db(): no active call.");
2594                 return;
2595         }
2596         if (st->volrecv){
2597                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_DB_GAIN,&gain);
2598         }else ms_warning("Could not apply gain: gain control wasn't activated.");
2599 }
2600
2601 /**
2602  * Get playback gain in db before entering  sound card.
2603  *
2604  * @ingroup media_parameters
2605 **/
2606 float linphone_core_get_playback_gain_db(LinphoneCore *lc) {
2607         return lc->sound_conf.soft_play_lev;
2608 }
2609
2610 /**
2611  * Set sound playback level in 0-100 scale
2612  *
2613  * @ingroup media_parameters
2614 **/
2615 void linphone_core_set_play_level(LinphoneCore *lc, int level){
2616         MSSndCard *sndcard;
2617         lc->sound_conf.play_lev=level;
2618         sndcard=lc->sound_conf.play_sndcard;
2619         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_PLAYBACK,level);
2620 }
2621
2622 /**
2623  * Set sound capture level in 0-100 scale
2624  *
2625  * @ingroup media_parameters
2626 **/
2627 void linphone_core_set_rec_level(LinphoneCore *lc, int level)
2628 {
2629         MSSndCard *sndcard;
2630         lc->sound_conf.rec_lev=level;
2631         sndcard=lc->sound_conf.capt_sndcard;
2632         if (sndcard) ms_snd_card_set_level(sndcard,MS_SND_CARD_CAPTURE,level);
2633 }
2634
2635 static MSSndCard *get_card_from_string_id(const char *devid, unsigned int cap){
2636         MSSndCard *sndcard=NULL;
2637         if (devid!=NULL){
2638                 sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
2639                 if (sndcard!=NULL &&
2640                         (ms_snd_card_get_capabilities(sndcard) & cap)==0 ){
2641                         ms_warning("%s card does not have the %s capability, ignoring.",
2642                                 devid,
2643                                 cap==MS_SND_CARD_CAP_CAPTURE ? "capture" : "playback");
2644                         sndcard=NULL;
2645                 }
2646         }
2647         if (sndcard==NULL) {
2648                 /* get a card that has read+write capabilities */
2649                 sndcard=ms_snd_card_manager_get_default_card(ms_snd_card_manager_get());
2650                 /* otherwise refine to the first card having the right capability*/
2651                 if (sndcard==NULL){
2652                         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
2653                         for(;elem!=NULL;elem=elem->next){
2654                                 sndcard=(MSSndCard*)elem->data;
2655                                 if (ms_snd_card_get_capabilities(sndcard) & cap) break;
2656                         }
2657                 }
2658                 if (sndcard==NULL){/*looks like a bug! take the first one !*/
2659                         const MSList *elem=ms_snd_card_manager_get_list(ms_snd_card_manager_get());
2660                         if (elem) sndcard=(MSSndCard*)elem->data;
2661         }
2662         }
2663         if (sndcard==NULL) ms_error("Could not find a suitable soundcard !");
2664         return sndcard;
2665 }
2666
2667 /**
2668  * Returns true if the specified sound device can capture sound.
2669  *
2670  * @ingroup media_parameters
2671  * @param lc The LinphoneCore object
2672  * @param devid the device name as returned by linphone_core_get_sound_devices()
2673 **/
2674 bool_t linphone_core_sound_device_can_capture(LinphoneCore *lc, const char *devid){
2675         MSSndCard *sndcard;
2676         sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
2677         if (sndcard!=NULL && (ms_snd_card_get_capabilities(sndcard) & MS_SND_CARD_CAP_CAPTURE)) return TRUE;
2678         return FALSE;
2679 }
2680
2681 /**
2682  * Returns true if the specified sound device can play sound.
2683  *
2684  * @ingroup media_parameters
2685  * @param lc The LinphoneCore object
2686  * @param devid the device name as returned by linphone_core_get_sound_devices()
2687 **/
2688 bool_t linphone_core_sound_device_can_playback(LinphoneCore *lc, const char *devid){
2689         MSSndCard *sndcard;
2690         sndcard=ms_snd_card_manager_get_card(ms_snd_card_manager_get(),devid);
2691         if (sndcard!=NULL && (ms_snd_card_get_capabilities(sndcard) & MS_SND_CARD_CAP_PLAYBACK)) return TRUE;
2692         return FALSE;
2693 }
2694
2695 /**
2696  * Sets the sound device used for ringing.
2697  *
2698  * @ingroup media_parameters
2699  * @param lc The LinphoneCore object
2700  * @param devid the device name as returned by linphone_core_get_sound_devices()
2701 **/
2702 int linphone_core_set_ringer_device(LinphoneCore *lc, const char * devid){
2703         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_PLAYBACK);
2704         lc->sound_conf.ring_sndcard=card;
2705         if (card && linphone_core_ready(lc))
2706                 lp_config_set_string(lc->config,"sound","ringer_dev_id",ms_snd_card_get_string_id(card));
2707         return 0;
2708 }
2709
2710 /**
2711  * Sets the sound device used for playback.
2712  *
2713  * @ingroup media_parameters
2714  * @param lc The LinphoneCore object
2715  * @param devid the device name as returned by linphone_core_get_sound_devices()
2716 **/
2717 int linphone_core_set_playback_device(LinphoneCore *lc, const char * devid){
2718         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_PLAYBACK);
2719         lc->sound_conf.play_sndcard=card;
2720         if (card &&  linphone_core_ready(lc))
2721                 lp_config_set_string(lc->config,"sound","playback_dev_id",ms_snd_card_get_string_id(card));
2722         return 0;
2723 }
2724
2725 /**
2726  * Sets the sound device used for capture.
2727  *
2728  * @ingroup media_parameters
2729  * @param lc The LinphoneCore object
2730  * @param devid the device name as returned by linphone_core_get_sound_devices()
2731 **/
2732 int linphone_core_set_capture_device(LinphoneCore *lc, const char * devid){
2733         MSSndCard *card=get_card_from_string_id(devid,MS_SND_CARD_CAP_CAPTURE);
2734         lc->sound_conf.capt_sndcard=card;
2735         if (card &&  linphone_core_ready(lc))
2736                 lp_config_set_string(lc->config,"sound","capture_dev_id",ms_snd_card_get_string_id(card));
2737         return 0;
2738 }
2739
2740 /**
2741  * Returns the name of the currently assigned sound device for ringing.
2742  *
2743  * @ingroup media_parameters
2744  * @param lc The LinphoneCore object
2745 **/
2746 const char * linphone_core_get_ringer_device(LinphoneCore *lc)
2747 {
2748         if (lc->sound_conf.ring_sndcard) return ms_snd_card_get_string_id(lc->sound_conf.ring_sndcard);
2749         return NULL;
2750 }
2751
2752 /**
2753  * Returns the name of the currently assigned sound device for playback.
2754  *
2755  * @ingroup media_parameters
2756  * @param lc The LinphoneCore object
2757 **/
2758 const char * linphone_core_get_playback_device(LinphoneCore *lc)
2759 {
2760         return lc->sound_conf.play_sndcard ? ms_snd_card_get_string_id(lc->sound_conf.play_sndcard) : NULL;
2761 }
2762
2763 /**
2764  * Returns the name of the currently assigned sound device for capture.
2765  *
2766  * @ingroup media_parameters
2767  * @param lc The LinphoneCore object
2768 **/
2769 const char * linphone_core_get_capture_device(LinphoneCore *lc)
2770 {
2771         return lc->sound_conf.capt_sndcard ? ms_snd_card_get_string_id(lc->sound_conf.capt_sndcard) : NULL;
2772 }
2773
2774 /**
2775  * Returns an unmodifiable array of available sound devices.
2776  *
2777  * The array is NULL terminated.
2778  *
2779  * @ingroup media_parameters
2780  * @param lc The LinphoneCore object
2781 **/
2782 const char**  linphone_core_get_sound_devices(LinphoneCore *lc){
2783         build_sound_devices_table(lc);
2784         return lc->sound_conf.cards;
2785 }
2786
2787 /**
2788  * Returns an unmodifiable array of available video capture devices.
2789  *
2790  * @ingroup media_parameters
2791  * The array is NULL terminated.
2792 **/
2793 const char**  linphone_core_get_video_devices(const LinphoneCore *lc){
2794         return lc->video_conf.cams;
2795 }
2796
2797 char linphone_core_get_sound_source(LinphoneCore *lc)
2798 {
2799         return lc->sound_conf.source;
2800 }
2801
2802 void linphone_core_set_sound_source(LinphoneCore *lc, char source)
2803 {
2804         MSSndCard *sndcard=lc->sound_conf.capt_sndcard;
2805         lc->sound_conf.source=source;
2806         if (!sndcard) return;
2807         switch(source){
2808                 case 'm':
2809                         ms_snd_card_set_capture(sndcard,MS_SND_CARD_MIC);
2810                         break;
2811                 case 'l':
2812                         ms_snd_card_set_capture(sndcard,MS_SND_CARD_LINE);
2813                         break;
2814         }
2815
2816 }
2817
2818
2819 /**
2820  * Sets the path to a wav file used for ringing.
2821  *
2822  * @param path The file must be a wav 16bit linear. Local ring is disabled if null
2823  * @param lc The LinphoneCore object
2824  *
2825  * @ingroup media_parameters
2826 **/
2827 void linphone_core_set_ring(LinphoneCore *lc,const char *path){
2828         if (lc->sound_conf.local_ring!=0){
2829                 ms_free(lc->sound_conf.local_ring);
2830                 lc->sound_conf.local_ring=NULL;
2831         }
2832         if (path)
2833                 lc->sound_conf.local_ring=ms_strdup(path);
2834         if ( linphone_core_ready(lc) && lc->sound_conf.local_ring)
2835                 lp_config_set_string(lc->config,"sound","local_ring",lc->sound_conf.local_ring);
2836 }
2837
2838 /**
2839  * Returns the path to the wav file used for ringing.
2840  *
2841  * @param lc The LinphoneCore object
2842  * @ingroup media_parameters
2843 **/
2844 const char *linphone_core_get_ring(const LinphoneCore *lc){
2845         return lc->sound_conf.local_ring;
2846 }
2847
2848 static void notify_end_of_ring(void *ud, MSFilter *f, unsigned int event, void *arg){
2849         LinphoneCore *lc=(LinphoneCore*)ud;
2850         lc->preview_finished=1;
2851 }
2852
2853 int linphone_core_preview_ring(LinphoneCore *lc, const char *ring,LinphoneCoreCbFunc func,void * userdata)
2854 {
2855         if (lc->ringstream!=0){
2856                 ms_warning("Cannot start ring now,there's already a ring being played");
2857                 return -1;
2858         }
2859         lc_callback_obj_init(&lc->preview_finished_cb,func,userdata);
2860         lc->preview_finished=0;
2861         if (lc->sound_conf.ring_sndcard!=NULL){
2862                 MSSndCard *ringcard=lc->sound_conf.lsd_card ? lc->sound_conf.lsd_card : lc->sound_conf.ring_sndcard;
2863                 lc->ringstream=ring_start_with_cb(ring,2000,ringcard,notify_end_of_ring,(void *)lc);
2864         }
2865         return 0;
2866 }
2867
2868 /**
2869  * Sets the path to a wav file used for ringing back.
2870  *
2871  * Ringback means the ring that is heard when it's ringing at the remote party.
2872  * The file must be a wav 16bit linear.
2873  *
2874  * @ingroup media_parameters
2875 **/
2876 void linphone_core_set_ringback(LinphoneCore *lc, const char *path){
2877         if (lc->sound_conf.remote_ring!=0){
2878                 ms_free(lc->sound_conf.remote_ring);
2879         }
2880         lc->sound_conf.remote_ring=ms_strdup(path);
2881 }
2882
2883 /**
2884  * Returns the path to the wav file used for ringing back.
2885  *
2886  * @ingroup media_parameters
2887 **/
2888 const char * linphone_core_get_ringback(const LinphoneCore *lc){
2889         return lc->sound_conf.remote_ring;
2890 }
2891
2892 /**
2893  * Enables or disable echo cancellation. Value is saved an used for subsequent calls
2894  *
2895  * @ingroup media_parameters
2896 **/
2897 void linphone_core_enable_echo_cancellation(LinphoneCore *lc, bool_t val){
2898         lc->sound_conf.ec=val;
2899         if ( linphone_core_ready(lc))
2900                 lp_config_set_int(lc->config,"sound","echocancellation",val);
2901 }
2902
2903
2904 /**
2905  * Returns TRUE if echo cancellation is enabled.
2906  *
2907  * @ingroup media_parameters
2908 **/
2909 bool_t linphone_core_echo_cancellation_enabled(LinphoneCore *lc){
2910         return lc->sound_conf.ec;
2911 }
2912
2913 void linphone_core_enable_echo_limiter(LinphoneCore *lc, bool_t val){
2914         lc->sound_conf.ea=val;
2915 }
2916
2917 bool_t linphone_core_echo_limiter_enabled(const LinphoneCore *lc){
2918         return lc->sound_conf.ea;
2919 }
2920
2921 /**
2922  * Mutes or unmutes the local microphone.
2923  *
2924  * @ingroup media_parameters
2925 **/
2926 void linphone_core_mute_mic(LinphoneCore *lc, bool_t val){
2927         LinphoneCall *call=linphone_core_get_current_call(lc);
2928         if (call==NULL){
2929                 ms_warning("linphone_core_mute_mic(): No current call !");
2930                 return;
2931         }
2932         if (call->audiostream!=NULL){
2933                 audio_stream_set_mic_gain(call->audiostream,
2934                         (val==TRUE) ? 0 : lp_config_get_float(lc->config,"sound","mic_gain",1)); 
2935                 if ( linphone_core_get_rtp_no_xmit_on_audio_mute(lc) ){
2936                         audio_stream_mute_rtp(call->audiostream,val);
2937                 }
2938                 call->audio_muted=val;
2939         }
2940 }
2941
2942 bool_t linphone_core_is_mic_muted(LinphoneCore *lc) {
2943         LinphoneCall *call=linphone_core_get_current_call(lc);
2944         if (call==NULL){
2945                 ms_warning("linphone_core_is_mic_muted(): No current call !");
2946                 return FALSE;
2947         }
2948         return call->audio_muted;
2949 }
2950
2951 // returns rtp transmission status for an active stream
2952 // if audio is muted and config parameter rtp_no_xmit_on_audio_mute 
2953 // was set on then rtp transmission is also muted
2954 bool_t linphone_core_is_rtp_muted(LinphoneCore *lc){
2955         LinphoneCall *call=linphone_core_get_current_call(lc);
2956         if (call==NULL){
2957                 ms_warning("linphone_core_is_mic_muted(): No current call !");
2958                 return FALSE;
2959         }
2960         if( linphone_core_get_rtp_no_xmit_on_audio_mute(lc)){
2961                 return call->audio_muted;
2962         }
2963         return FALSE;
2964 }
2965
2966 void linphone_core_enable_agc(LinphoneCore *lc, bool_t val){
2967         lc->sound_conf.agc=val;
2968 }
2969
2970 bool_t linphone_core_agc_enabled(const LinphoneCore *lc){
2971         return lc->sound_conf.agc;
2972 }
2973
2974 /**
2975  * Send the specified dtmf.
2976  *
2977  * @ingroup media_parameters
2978  * This function only works during calls. The dtmf is automatically played to the user.
2979  * @param lc The LinphoneCore object
2980  * @param dtmf The dtmf name specified as a char, such as '0', '#' etc...
2981  *
2982 **/
2983 void linphone_core_send_dtmf(LinphoneCore *lc, char dtmf)
2984 {
2985         LinphoneCall *call=linphone_core_get_current_call(lc);
2986         if (call==NULL){
2987                 ms_warning("linphone_core_send_dtmf(): no active call");
2988                 return;
2989         }
2990         /*By default we send DTMF RFC2833 if we do not have enabled SIP_INFO but we can also send RFC2833 and SIP_INFO*/
2991         if (linphone_core_get_use_rfc2833_for_dtmf(lc)!=0 || linphone_core_get_use_info_for_dtmf(lc)==0)
2992         {
2993                 /* In Band DTMF */
2994                 if (call->audiostream!=NULL){
2995                         audio_stream_send_dtmf(call->audiostream,dtmf);
2996                 }
2997                 else
2998                 {
2999                         ms_error("we cannot send RFC2833 dtmf when we are not in communication");
3000                 }
3001         }
3002         if (linphone_core_get_use_info_for_dtmf(lc)!=0){
3003                 /* Out of Band DTMF (use INFO method) */
3004                 sal_call_send_dtmf(call->op,dtmf);
3005         }
3006 }
3007
3008 void linphone_core_set_stun_server(LinphoneCore *lc, const char *server){
3009         if (lc->net_conf.stun_server!=NULL)
3010                 ms_free(lc->net_conf.stun_server);
3011         if (server)
3012                 lc->net_conf.stun_server=ms_strdup(server);
3013         else lc->net_conf.stun_server=NULL;
3014 }
3015
3016 const char * linphone_core_get_stun_server(const LinphoneCore *lc){
3017         return lc->net_conf.stun_server;
3018 }
3019
3020 const char * linphone_core_get_relay_addr(const LinphoneCore *lc){
3021         return lc->net_conf.relay;
3022 }
3023
3024 int linphone_core_set_relay_addr(LinphoneCore *lc, const char *addr){
3025         if (lc->net_conf.relay!=NULL){
3026                 ms_free(lc->net_conf.relay);
3027                 lc->net_conf.relay=NULL;
3028         }
3029         if (addr){
3030                 lc->net_conf.relay=ms_strdup(addr);
3031         }
3032         return 0;
3033 }
3034
3035 void linphone_core_set_nat_address(LinphoneCore *lc, const char *addr)
3036 {
3037         if (lc->net_conf.nat_address!=NULL){
3038                 ms_free(lc->net_conf.nat_address);
3039         }
3040         if (addr!=NULL) lc->net_conf.nat_address=ms_strdup(addr);
3041         else lc->net_conf.nat_address=NULL;
3042         if (lc->sip_conf.contact) update_primary_contact(lc);
3043 }
3044
3045 const char *linphone_core_get_nat_address(const LinphoneCore *lc) {
3046         return lc->net_conf.nat_address;
3047 }
3048
3049 const char *linphone_core_get_nat_address_resolved(LinphoneCore *lc)
3050 {
3051         struct sockaddr_storage ss;
3052         socklen_t ss_len;
3053         int error;
3054         char ipstring [INET6_ADDRSTRLEN];
3055
3056         if (parse_hostname_to_addr (lc->net_conf.nat_address, &ss, &ss_len)<0) {
3057                 return lc->net_conf.nat_address;
3058         }
3059
3060         error = getnameinfo((struct sockaddr *)&ss, ss_len,
3061                 ipstring, sizeof(ipstring), NULL, 0, NI_NUMERICHOST);
3062         if (error) {
3063                 return lc->net_conf.nat_address;
3064         } 
3065         
3066         if (lc->net_conf.nat_address_ip!=NULL){
3067                 ms_free(lc->net_conf.nat_address_ip);
3068         }
3069         lc->net_conf.nat_address_ip = ms_strdup (ipstring);
3070         return lc->net_conf.nat_address_ip;
3071 }
3072
3073 void linphone_core_set_firewall_policy(LinphoneCore *lc, LinphoneFirewallPolicy pol){
3074         lc->net_conf.firewall_policy=pol;
3075         if (lc->sip_conf.contact) update_primary_contact(lc);
3076 }
3077
3078 LinphoneFirewallPolicy linphone_core_get_firewall_policy(const LinphoneCore *lc){
3079         return lc->net_conf.firewall_policy;
3080 }
3081
3082 /**
3083  * Get the list of call logs (past calls).
3084  *
3085  * @ingroup call_logs
3086 **/
3087 const MSList * linphone_core_get_call_logs(LinphoneCore *lc){
3088         lc->missed_calls=0;
3089         return lc->call_logs;
3090 }
3091
3092 /**
3093  * Erase the call log.
3094  *
3095  * @ingroup call_logs
3096 **/
3097 void linphone_core_clear_call_logs(LinphoneCore *lc){
3098         lc->missed_calls=0;
3099         ms_list_for_each(lc->call_logs,(void (*)(void*))linphone_call_log_destroy);
3100         lc->call_logs=ms_list_free(lc->call_logs);
3101         call_logs_write_to_config_file(lc);
3102 }
3103
3104 static void toggle_video_preview(LinphoneCore *lc, bool_t val){
3105 #ifdef VIDEO_ENABLED
3106         if (val){
3107                 if (lc->previewstream==NULL){
3108                         lc->previewstream=video_preview_new();
3109                         video_preview_set_size(lc->previewstream,lc->video_conf.vsize);
3110                         if (lc->video_conf.displaytype)
3111                                 video_preview_set_display_filter_name(lc->previewstream,lc->video_conf.displaytype);
3112                         if (lc->preview_window_id!=0)
3113                                 video_preview_set_native_window_id(lc->previewstream,lc->preview_window_id);
3114                         video_preview_start(lc->previewstream,lc->video_conf.device);
3115                 }
3116         }else{
3117                 if (lc->previewstream!=NULL){
3118                         video_preview_stop(lc->previewstream);
3119                         lc->previewstream=NULL;
3120                 }
3121         }
3122 #endif
3123 }
3124
3125 /**
3126  * Enables video globally.
3127  *
3128  * @ingroup media_parameters
3129  * This function does not have any effect during calls. It just indicates LinphoneCore to
3130  * initiate future calls with video or not. The two boolean parameters indicate in which
3131  * direction video is enabled. Setting both to false disables video entirely.
3132  *
3133  * @param lc The LinphoneCore object
3134  * @param vcap_enabled indicates whether video capture is enabled
3135  * @param display_enabled indicates whether video display should be shown
3136  *
3137 **/
3138 void linphone_core_enable_video(LinphoneCore *lc, bool_t vcap_enabled, bool_t display_enabled){
3139 #ifndef VIDEO_ENABLED
3140         if (vcap_enabled || display_enabled)
3141                 ms_warning("This version of linphone was built without video support.");
3142 #endif
3143         lc->video_conf.capture=vcap_enabled;
3144         lc->video_conf.display=display_enabled;
3145
3146         /* need to re-apply network bandwidth settings*/
3147         linphone_core_set_download_bandwidth(lc,
3148                 linphone_core_get_download_bandwidth(lc));
3149         linphone_core_set_upload_bandwidth(lc,
3150                 linphone_core_get_upload_bandwidth(lc));
3151 }
3152
3153 /**
3154  * Returns TRUE if video is enabled, FALSE otherwise.
3155  * @ingroup media_parameters
3156 **/
3157 bool_t linphone_core_video_enabled(LinphoneCore *lc){
3158         return (lc->video_conf.display || lc->video_conf.capture);
3159 }
3160
3161 /**
3162  * Controls video preview enablement.
3163  *
3164  * @ingroup media_parameters
3165  * Video preview refers to the action of displaying the local webcam image
3166  * to the user while not in call.
3167 **/
3168 void linphone_core_enable_video_preview(LinphoneCore *lc, bool_t val){
3169         lc->video_conf.show_local=val;
3170 }
3171
3172 /**
3173  * Returns TRUE if video previewing is enabled.
3174  * @ingroup media_parameters
3175 **/
3176 bool_t linphone_core_video_preview_enabled(const LinphoneCore *lc){
3177         return lc->video_conf.show_local;
3178 }
3179
3180 /**
3181  * Enables or disable self view during calls.
3182  *
3183  * @ingroup media_parameters
3184  * Self-view refers to having local webcam image inserted in corner
3185  * of the video window during calls.
3186  * This function works at any time, including during calls.
3187 **/
3188 void linphone_core_enable_self_view(LinphoneCore *lc, bool_t val){
3189 #ifdef VIDEO_ENABLED
3190         LinphoneCall *call=linphone_core_get_current_call (lc);
3191         lc->video_conf.selfview=val;
3192         if (call && call->videostream){
3193                 video_stream_enable_self_view(call->videostream,val);
3194         }
3195 #endif
3196 }
3197
3198 /**
3199  * Returns TRUE if self-view is enabled, FALSE otherwise.
3200  *
3201  * @ingroup media_parameters
3202  *
3203  * Refer to linphone_core_enable_self_view() for details.
3204 **/
3205 bool_t linphone_core_self_view_enabled(const LinphoneCore *lc){
3206         return lc->video_conf.selfview;
3207 }
3208
3209 /**
3210  * Sets the active video device.
3211  *
3212  * @ingroup media_parameters
3213  * @param lc The LinphoneCore object
3214  * @param id the name of the video device as returned by linphone_core_get_video_devices()
3215 **/
3216 int linphone_core_set_video_device(LinphoneCore *lc, const char *id){
3217         MSWebCam *olddev=lc->video_conf.device;
3218         const char *vd;
3219         if (id!=NULL){
3220                 lc->video_conf.device=ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),id);
3221                 if (lc->video_conf.device==NULL){
3222                         ms_warning("Could not found video device %s",id);
3223                 }
3224         }
3225         if (lc->video_conf.device==NULL)
3226                 lc->video_conf.device=ms_web_cam_manager_get_default_cam(ms_web_cam_manager_get());
3227         if (olddev!=NULL && olddev!=lc->video_conf.device){
3228                 toggle_video_preview(lc,FALSE);/*restart the video local preview*/
3229         }
3230         if ( linphone_core_ready(lc) && lc->video_conf.device){
3231                 vd=ms_web_cam_get_string_id(lc->video_conf.device);
3232                 if (vd && strstr(vd,"Static picture")!=NULL){
3233                         vd=NULL;
3234                 }
3235                 lp_config_set_string(lc->config,"video","device",vd);
3236         }
3237         return 0;
3238 }
3239
3240 /**
3241  * Returns the name of the currently active video device.
3242  *
3243  * @param lc The LinphoneCore object
3244  * @ingroup media_parameters
3245 **/
3246 const char *linphone_core_get_video_device(const LinphoneCore *lc){
3247         if (lc->video_conf.device) return ms_web_cam_get_string_id(lc->video_conf.device);
3248         return NULL;
3249 }
3250
3251 #ifdef VIDEO_ENABLED
3252 static VideoStream * get_active_video_stream(LinphoneCore *lc){
3253         VideoStream *vs = NULL;
3254         LinphoneCall *call=linphone_core_get_current_call (lc);
3255         /* Select the video stream from the call in the first place */
3256         if (call && call->videostream) {
3257                 vs = call->videostream;
3258         }
3259         /* If not in call, select the video stream from the preview */
3260         if (vs == NULL && lc->previewstream) {
3261                 vs = lc->previewstream;
3262         }
3263         return vs;
3264 }
3265 #endif
3266
3267 int linphone_core_set_static_picture(LinphoneCore *lc, const char *path) {
3268 #ifdef VIDEO_ENABLED
3269         VideoStream *vs=get_active_video_stream(lc);
3270         /* If we have a video stream (either preview, either from call), we
3271                  have a source and it is using the static picture filter, then
3272                  force the filter to use that picture. */
3273         if (vs && vs->source) {
3274                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
3275                         ms_filter_call_method(vs->source, MS_STATIC_IMAGE_SET_IMAGE,
3276                                                                                                                 (void *)path);
3277                 }
3278         }
3279         /* Tell the static image filter to use that image from now on so
3280                  that the image will be used next time it has to be read */
3281         ms_static_image_set_default_image(path);
3282 #else
3283         ms_warning("Video support not compiled.");
3284 #endif
3285         return 0;
3286 }
3287
3288 int linphone_core_set_static_picture_fps(LinphoneCore *lc, float fps) {
3289 #ifdef VIDEO_ENABLED
3290         VideoStream *vs = NULL;
3291
3292         vs=get_active_video_stream(lc);
3293         
3294         /* If we have a video stream (either preview, either from call), we
3295                  have a source and it is using the static picture filter, then
3296                  force the filter to use that picture. */
3297         if (vs && vs->source) {
3298                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
3299                         ms_filter_call_method(vs->source, MS_FILTER_SET_FPS,(void *)&fps);
3300                 }
3301         }
3302 #else
3303         ms_warning("Video support not compiled.");
3304 #endif
3305         return 0;
3306 }
3307
3308 float linphone_core_get_static_picture_fps(LinphoneCore *lc) {
3309 #ifdef VIDEO_ENABLED
3310         VideoStream *vs = NULL;
3311         vs=get_active_video_stream(lc);
3312         /* If we have a video stream (either preview, either from call), we
3313                  have a source and it is using the static picture filter, then
3314                  force the filter to use that picture. */
3315         if (vs && vs->source) {
3316                 if (ms_filter_get_id(vs->source) == MS_STATIC_IMAGE_ID) {
3317                   
3318                         float fps;
3319                   
3320                         ms_filter_call_method(vs->source, MS_FILTER_GET_FPS,(void *)&fps);
3321                         return fps;
3322                 }
3323         }
3324 #else
3325         ms_warning("Video support not compiled.");
3326 #endif
3327         return 0;
3328 }
3329
3330 /**
3331  * Returns the native window handle of the video window, casted as an unsigned long.
3332  *
3333  * @ingroup media_parameters
3334 **/
3335 unsigned long linphone_core_get_native_video_window_id(const LinphoneCore *lc){
3336 #ifdef VIDEO_ENABLED
3337         LinphoneCall *call=linphone_core_get_current_call (lc);
3338         if (call && call->videostream)
3339                 return video_stream_get_native_window_id(call->videostream);
3340         if (lc->previewstream)
3341                 return video_stream_get_native_window_id(lc->previewstream);
3342 #endif
3343         return lc->video_window_id;
3344 }
3345
3346 /**
3347  * Set the native video window id where the video is to be displayed.
3348  * If not set the core will create its own window.
3349 **/
3350 void linphone_core_set_native_video_window_id(LinphoneCore *lc, unsigned long id){
3351 #ifdef VIDEO_ENABLED
3352         LinphoneCall *call=linphone_core_get_current_call(lc);
3353         lc->video_window_id=id;
3354         if (call!=NULL && call->videostream){
3355                 video_stream_set_native_window_id(call->videostream,id);
3356         }
3357 #endif
3358 }
3359
3360 /**
3361  * Returns the native window handle of the video preview window, casted as an unsigned long.
3362  *
3363  * @ingroup media_parameters
3364 **/
3365 unsigned long linphone_core_get_native_preview_window_id(const LinphoneCore *lc){
3366 #ifdef VIDEO_ENABLED
3367         LinphoneCall *call=linphone_core_get_current_call (lc);
3368         if (call && call->videostream)
3369                 return video_stream_get_native_preview_window_id(call->videostream);
3370         if (lc->previewstream)
3371                 return video_preview_get_native_window_id(lc->previewstream);
3372 #endif
3373         return lc->preview_window_id;
3374 }
3375
3376 /**
3377  * Set the native window id where the preview video (local camera) is to be displayed.
3378  * This has to be used in conjonction with linphone_core_use_preview_window().
3379  * If not set the core will create its own window.
3380 **/
3381 void linphone_core_set_native_preview_window_id(LinphoneCore *lc, unsigned long id){
3382         lc->preview_window_id=id;
3383 }
3384
3385 /**
3386  * Tells the core to use a separate window for local camera preview video, instead of
3387  * inserting local view within the remote video window.
3388  *
3389 **/
3390 void linphone_core_use_preview_window(LinphoneCore *lc, bool_t yesno){
3391         lc->use_preview_window=yesno;
3392 }
3393
3394 static MSVideoSizeDef supported_resolutions[]={
3395 #ifdef ENABLE_HD
3396         {       {MS_VIDEO_SIZE_1080P_W,MS_VIDEO_SIZE_1080P_H}   ,       "1080p" },
3397         {       {MS_VIDEO_SIZE_720P_W,MS_VIDEO_SIZE_720P_H}     ,       "1080p" },
3398 #endif
3399         {       {MS_VIDEO_SIZE_SVGA_W,MS_VIDEO_SIZE_SVGA_H}     ,       "svga"  },
3400         {       {MS_VIDEO_SIZE_4CIF_W,MS_VIDEO_SIZE_4CIF_H}     ,       "4cif"  },
3401         {       {MS_VIDEO_SIZE_VGA_W,MS_VIDEO_SIZE_VGA_H}       ,       "vga"   },
3402         {       {MS_VIDEO_SIZE_CIF_W,MS_VIDEO_SIZE_CIF_H}       ,       "cif"   },
3403         {       {MS_VIDEO_SIZE_QVGA_W,MS_VIDEO_SIZE_QVGA_H}     ,       "qvga"  },
3404         {       {MS_VIDEO_SIZE_QVGA_H,MS_VIDEO_SIZE_QVGA_W}     ,       "qvga-portrait" },
3405         {       {MS_VIDEO_SIZE_QCIF_W,MS_VIDEO_SIZE_QCIF_H}     ,       "qcif"  },
3406         {       {MS_VIDEO_SIZE_QCIF_H,MS_VIDEO_SIZE_QCIF_W}     ,       "qcif-portrait" },
3407         {       {0,0}                   ,       NULL    }
3408 };
3409
3410 /**
3411  * Returns the zero terminated table of supported video resolutions.
3412  *
3413  * @ingroup media_parameters
3414 **/
3415 const MSVideoSizeDef *linphone_core_get_supported_video_sizes(LinphoneCore *lc){
3416         return supported_resolutions;
3417 }
3418
3419 static MSVideoSize video_size_get_by_name(const char *name){
3420         MSVideoSizeDef *pdef=supported_resolutions;
3421         MSVideoSize null_vsize={0,0};
3422         for(;pdef->name!=NULL;pdef++){
3423                 if (strcasecmp(name,pdef->name)==0){
3424                         return pdef->vsize;
3425                 }
3426         }
3427         ms_warning("Video resolution %s is not supported in linphone.",name);
3428         return null_vsize;
3429 }
3430
3431 static const char *video_size_get_name(MSVideoSize vsize){
3432         MSVideoSizeDef *pdef=supported_resolutions;
3433         for(;pdef->name!=NULL;pdef++){
3434                 if (pdef->vsize.width==vsize.width && pdef->vsize.height==vsize.height){
3435                         return pdef->name;
3436                 }
3437         }
3438         return NULL;
3439 }
3440
3441 static bool_t video_size_supported(MSVideoSize vsize){
3442         if (video_size_get_name(vsize)) return TRUE;
3443         ms_warning("Video resolution %ix%i is not supported in linphone.",vsize.width,vsize.height);
3444         return FALSE;
3445 }
3446
3447 /**
3448  * Sets the preferred video size.
3449  *
3450  * @ingroup media_parameters
3451  * This applies only to the stream that is captured and sent to the remote party,
3452  * since we accept all standard video size on the receive path.
3453 **/
3454 void linphone_core_set_preferred_video_size(LinphoneCore *lc, MSVideoSize vsize){
3455         if (video_size_supported(vsize)){
3456                 MSVideoSize oldvsize=lc->video_conf.vsize;
3457                 lc->video_conf.vsize=vsize;
3458                 if (!ms_video_size_equal(oldvsize,vsize) && lc->previewstream!=NULL){
3459                         toggle_video_preview(lc,FALSE);
3460                         toggle_video_preview(lc,TRUE);
3461                 }
3462                 if ( linphone_core_ready(lc))
3463                         lp_config_set_string(lc->config,"video","size",video_size_get_name(vsize));
3464         }
3465 }
3466
3467 /**
3468  * Sets the preferred video size by its name.
3469  *
3470  * @ingroup media_parameters
3471  * This is identical to linphone_core_set_preferred_video_size() except
3472  * that it takes the name of the video resolution as input.
3473  * Video resolution names are: qcif, svga, cif, vga, 4cif, svga ...
3474 **/
3475 void linphone_core_set_preferred_video_size_by_name(LinphoneCore *lc, const char *name){
3476         MSVideoSize vsize=video_size_get_by_name(name);
3477         MSVideoSize default_vsize={MS_VIDEO_SIZE_CIF_W,MS_VIDEO_SIZE_CIF_H};
3478         if (vsize.width!=0)     linphone_core_set_preferred_video_size(lc,vsize);
3479         else linphone_core_set_preferred_video_size(lc,default_vsize);
3480 }
3481
3482 /**
3483  * Returns the current preferred video size for sending.
3484  *
3485  * @ingroup media_parameters
3486 **/
3487 MSVideoSize linphone_core_get_preferred_video_size(LinphoneCore *lc){
3488         return lc->video_conf.vsize;
3489 }
3490
3491 /**
3492  * Ask the core to stream audio from and to files, instead of using the soundcard.
3493 **/
3494 void linphone_core_use_files(LinphoneCore *lc, bool_t yesno){
3495         lc->use_files=yesno;
3496 }
3497
3498 /**
3499  * Sets a wav file to be played when putting somebody on hold,
3500  * or when files are used instead of soundcards (see linphone_core_use_files()).
3501  * 
3502  * The file must be a 16 bit linear wav file.
3503 **/
3504 void linphone_core_set_play_file(LinphoneCore *lc, const char *file){
3505         LinphoneCall *call=linphone_core_get_current_call(lc);
3506         if (lc->play_file!=NULL){
3507                 ms_free(lc->play_file);
3508                 lc->play_file=NULL;
3509         }
3510         if (file!=NULL) {
3511                 lc->play_file=ms_strdup(file);
3512                 if (call && call->audiostream && call->audiostream->ticker)
3513                         audio_stream_play(call->audiostream,file);
3514         }
3515 }
3516
3517
3518 /**
3519  * Sets a wav file where incoming stream is to be recorded,
3520  * when files are used instead of soundcards (see linphone_core_use_files()).
3521  * 
3522  * The file must be a 16 bit linear wav file.
3523 **/
3524 void linphone_core_set_record_file(LinphoneCore *lc, const char *file){
3525         LinphoneCall *call=linphone_core_get_current_call(lc);
3526         if (lc->rec_file!=NULL){
3527                 ms_free(lc->rec_file);
3528                 lc->rec_file=NULL;
3529         }
3530         if (file!=NULL) {
3531                 lc->rec_file=ms_strdup(file);
3532                 if (call && call->audiostream)
3533                         audio_stream_record(call->audiostream,file);
3534         }
3535 }
3536
3537
3538 static MSFilter *get_dtmf_gen(LinphoneCore *lc){
3539         LinphoneCall *call=linphone_core_get_current_call (lc);
3540         if (call){
3541                 AudioStream *stream=call->audiostream;
3542                 if (stream){
3543                         return stream->dtmfgen;
3544                 }
3545         }
3546         if (lc->ringstream==NULL){
3547                 float amp=0.1;
3548                 MSSndCard *ringcard=lc->sound_conf.lsd_card ?lc->sound_conf.lsd_card : lc->sound_conf.ring_sndcard;
3549                 lc->ringstream=ring_start(NULL,0,ringcard);
3550                 ms_filter_call_method(lc->ringstream->gendtmf,MS_DTMF_GEN_SET_DEFAULT_AMPLITUDE,&amp);
3551                 lc->dmfs_playing_start_time=time(NULL);
3552         }else{
3553                 if (lc->dmfs_playing_start_time!=0)
3554                         lc->dmfs_playing_start_time=time(NULL);
3555         }
3556         return lc->ringstream->gendtmf;
3557 }
3558
3559 /**
3560  * @ingroup media_parameters
3561  * Plays a dtmf sound to the local user.
3562  * @param lc #LinphoneCore
3563  * @param dtmf DTMF to play ['0'..'16'] | '#' | '#'
3564  * @param duration_ms duration in ms, -1 means play until next further call to #linphone_core_stop_dtmf()
3565 **/
3566 void linphone_core_play_dtmf(LinphoneCore *lc, char dtmf, int duration_ms){
3567         MSFilter *f=get_dtmf_gen(lc);
3568         if (f==NULL){
3569                 ms_error("No dtmf generator at this time !");
3570                 return;
3571         }
3572
3573         if (duration_ms>0)
3574                 ms_filter_call_method(f, MS_DTMF_GEN_PLAY, &dtmf);
3575         else ms_filter_call_method(f, MS_DTMF_GEN_START, &dtmf);
3576 }
3577
3578 /**
3579  * @ingroup media_parameters
3580  *
3581  * Stops playing a dtmf started by linphone_core_play_dtmf().
3582 **/
3583 void linphone_core_stop_dtmf(LinphoneCore *lc){
3584         MSFilter *f=get_dtmf_gen(lc);
3585         if (f!=NULL)
3586                 ms_filter_call_method_noarg (f, MS_DTMF_GEN_STOP);
3587 }
3588
3589
3590
3591 /**
3592  * Retrieves the user pointer that was given to linphone_core_new()
3593  *
3594  * @ingroup initializing
3595 **/
3596 void *linphone_core_get_user_data(LinphoneCore *lc){
3597         return lc->data;
3598 }
3599
3600 int linphone_core_get_mtu(const LinphoneCore *lc){
3601         return lc->net_conf.mtu;
3602 }
3603
3604 void linphone_core_set_mtu(LinphoneCore *lc, int mtu){
3605         lc->net_conf.mtu=mtu;
3606         if (mtu>0){
3607                 if (mtu<500){
3608                         ms_error("MTU too small !");
3609                         mtu=500;
3610                 }
3611                 ms_set_mtu(mtu);
3612                 ms_message("MTU is supposed to be %i, rtp payload max size will be %i",mtu, ms_get_payload_max_size());
3613         }else ms_set_mtu(0);//use mediastreamer2 default value
3614 }
3615
3616 void linphone_core_set_waiting_callback(LinphoneCore *lc, LinphoneWaitingCallback cb, void *user_context){
3617         lc->wait_cb=cb;
3618         lc->wait_ctx=user_context;
3619 }
3620
3621 void linphone_core_start_waiting(LinphoneCore *lc, const char *purpose){
3622         if (lc->wait_cb){
3623                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingStart,purpose,0);
3624         }
3625 }
3626
3627 void linphone_core_update_progress(LinphoneCore *lc, const char *purpose, float progress){
3628         if (lc->wait_cb){
3629                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingProgress,purpose,progress);
3630         }else{
3631 #ifdef WIN32
3632                 Sleep(50000);
3633 #else
3634                 usleep(50000);
3635 #endif
3636         }
3637 }
3638
3639 void linphone_core_stop_waiting(LinphoneCore *lc){
3640         if (lc->wait_cb){
3641                 lc->wait_ctx=lc->wait_cb(lc,lc->wait_ctx,LinphoneWaitingFinished,NULL,0);
3642         }
3643 }
3644
3645 void linphone_core_set_audio_transports(LinphoneCore *lc, RtpTransport *rtp, RtpTransport *rtcp){
3646         lc->a_rtp=rtp;
3647         lc->a_rtcp=rtcp;
3648 }
3649
3650 void linphone_core_set_video_transports(LinphoneCore *lc, RtpTransport *rtp, RtpTransport *rtcp){
3651         lc->v_rtp=rtp;
3652         lc->v_rtcp=rtcp;
3653 }
3654
3655 /**
3656  * Retrieve RTP statistics regarding current call.
3657  * @param local RTP statistics computed locally.
3658  * @param remote RTP statistics computed by far end (obtained via RTCP feedback).
3659  *
3660  * @note Remote RTP statistics is not implemented yet.
3661  *
3662  * @returns 0 or -1 if no call is running.
3663 **/
3664  
3665 int linphone_core_get_current_call_stats(LinphoneCore *lc, rtp_stats_t *local, rtp_stats_t *remote){
3666         LinphoneCall *call=linphone_core_get_current_call (lc);
3667         if (call!=NULL){
3668                 if (call->audiostream!=NULL){
3669                         memset(remote,0,sizeof(*remote));
3670                         audio_stream_get_local_rtp_stats (call->audiostream,local);
3671                         return 0;
3672                 }
3673         }
3674         return -1;
3675 }
3676
3677 void net_config_uninit(LinphoneCore *lc)
3678 {
3679         net_config_t *config=&lc->net_conf;
3680         lp_config_set_int(lc->config,"net","download_bw",config->download_bw);
3681         lp_config_set_int(lc->config,"net","upload_bw",config->upload_bw);
3682
3683         if (config->stun_server!=NULL){
3684                 lp_config_set_string(lc->config,"net","stun_server",config->stun_server);
3685                 ms_free(lc->net_conf.stun_server);
3686         }
3687         if (config->nat_address!=NULL){
3688                 lp_config_set_string(lc->config,"net","nat_address",config->nat_address);
3689                 ms_free(lc->net_conf.nat_address);
3690         }
3691         if (lc->net_conf.nat_address_ip !=NULL){
3692                 ms_free(lc->net_conf.nat_address_ip);
3693         }
3694         lp_config_set_int(lc->config,"net","firewall_policy",config->firewall_policy);
3695         lp_config_set_int(lc->config,"net","mtu",config->mtu);  
3696 }
3697
3698
3699 void sip_config_uninit(LinphoneCore *lc)
3700 {
3701         MSList *elem;
3702         int i;
3703         sip_config_t *config=&lc->sip_conf;
3704         lp_config_set_int(lc->config,"sip","sip_port",config->transports.udp_port);
3705         lp_config_set_int(lc->config,"sip","sip_tcp_port",config->transports.tcp_port);
3706         lp_config_set_int(lc->config,"sip","guess_hostname",config->guess_hostname);
3707         lp_config_set_string(lc->config,"sip","contact",config->contact);
3708         lp_config_set_int(lc->config,"sip","inc_timeout",config->inc_timeout);
3709         lp_config_set_int(lc->config,"sip","use_info",config->use_info);
3710         lp_config_set_int(lc->config,"sip","use_rfc2833",config->use_rfc2833);
3711         lp_config_set_int(lc->config,"sip","use_ipv6",config->ipv6_enabled);
3712         lp_config_set_int(lc->config,"sip","register_only_when_network_is_up",config->register_only_when_network_is_up);
3713
3714
3715         lp_config_set_int(lc->config,"sip","default_proxy",linphone_core_get_default_proxy(lc,NULL));
3716         
3717         for(elem=config->proxies,i=0;elem!=NULL;elem=ms_list_next(elem),i++){
3718                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)(elem->data);
3719                 linphone_proxy_config_write_to_config_file(lc->config,cfg,i);
3720                 linphone_proxy_config_edit(cfg);        /* to unregister */
3721         }
3722         /*to ensure remove configs are erased:*/
3723         linphone_proxy_config_write_to_config_file(lc->config,NULL,i);
3724
3725         for (i=0;i<20;i++){
3726                 sal_iterate(lc->sal);
3727 #ifndef WIN32
3728                 usleep(100000);
3729 #else
3730                 Sleep(100);
3731 #endif
3732         }
3733
3734         ms_list_for_each(config->proxies,(void (*)(void*)) linphone_proxy_config_destroy);
3735         ms_list_free(config->proxies);
3736         config->proxies=NULL;
3737         
3738         linphone_proxy_config_write_to_config_file(lc->config,NULL,i);  /*mark the end */
3739
3740         for(elem=lc->auth_info,i=0;elem!=NULL;elem=ms_list_next(elem),i++){
3741                 LinphoneAuthInfo *ai=(LinphoneAuthInfo*)(elem->data);
3742                 linphone_auth_info_write_config(lc->config,ai,i);
3743         }
3744         linphone_auth_info_write_config(lc->config,NULL,i); /* mark the end */
3745         ms_list_for_each(lc->auth_info,(void (*)(void*))linphone_auth_info_destroy);
3746         ms_list_free(lc->auth_info);
3747         lc->auth_info=NULL;
3748         
3749         sal_uninit(lc->sal);
3750         lc->sal=NULL;
3751
3752         if (lc->sip_conf.guessed_contact)
3753                 ms_free(lc->sip_conf.guessed_contact);
3754         if (config->contact)
3755                 ms_free(config->contact);
3756         
3757 }
3758
3759 void rtp_config_uninit(LinphoneCore *lc)
3760 {
3761         rtp_config_t *config=&lc->rtp_conf;
3762         lp_config_set_int(lc->config,"rtp","audio_rtp_port",config->audio_rtp_port);
3763         lp_config_set_int(lc->config,"rtp","video_rtp_port",config->video_rtp_port);
3764         lp_config_set_int(lc->config,"rtp","audio_jitt_comp",config->audio_jitt_comp);
3765         lp_config_set_int(lc->config,"rtp","video_jitt_comp",config->video_jitt_comp);
3766         lp_config_set_int(lc->config,"rtp","nortp_timeout",config->nortp_timeout);
3767 }
3768
3769 void sound_config_uninit(LinphoneCore *lc)
3770 {
3771         sound_config_t *config=&lc->sound_conf;
3772         ms_free(config->cards);
3773
3774         lp_config_set_string(lc->config,"sound","remote_ring",config->remote_ring);
3775
3776         if (config->local_ring) ms_free(config->local_ring);
3777         if (config->remote_ring) ms_free(config->remote_ring);
3778         ms_snd_card_manager_destroy();
3779 }
3780
3781 void video_config_uninit(LinphoneCore *lc)
3782 {
3783         lp_config_set_string(lc->config,"video","size",video_size_get_name(linphone_core_get_preferred_video_size(lc)));
3784         lp_config_set_int(lc->config,"video","display",lc->video_conf.display);
3785         lp_config_set_int(lc->config,"video","capture",lc->video_conf.capture);
3786         lp_config_set_int(lc->config,"video","show_local",linphone_core_video_preview_enabled(lc));
3787         lp_config_set_int(lc->config,"video","self_view",linphone_core_self_view_enabled(lc));
3788         if (lc->video_conf.cams)
3789                 ms_free(lc->video_conf.cams);
3790 }
3791
3792 void codecs_config_uninit(LinphoneCore *lc)
3793 {
3794         PayloadType *pt;
3795         codecs_config_t *config=&lc->codecs_conf;
3796         MSList *node;
3797         char key[50];
3798         int index;
3799         index=0;
3800         for(node=config->audio_codecs;node!=NULL;node=ms_list_next(node)){
3801                 pt=(PayloadType*)(node->data);
3802                 sprintf(key,"audio_codec_%i",index);
3803                 lp_config_set_string(lc->config,key,"mime",pt->mime_type);
3804                 lp_config_set_int(lc->config,key,"rate",pt->clock_rate);
3805                 lp_config_set_int(lc->config,key,"enabled",linphone_core_payload_type_enabled(lc,pt));
3806                 index++;
3807         }
3808         sprintf(key,"audio_codec_%i",index);
3809         lp_config_clean_section (lc->config,key);
3810         
3811         index=0;
3812         for(node=config->video_codecs;node!=NULL;node=ms_list_next(node)){
3813                 pt=(PayloadType*)(node->data);
3814                 sprintf(key,"video_codec_%i",index);
3815                 lp_config_set_string(lc->config,key,"mime",pt->mime_type);
3816                 lp_config_set_int(lc->config,key,"rate",pt->clock_rate);
3817                 lp_config_set_int(lc->config,key,"enabled",linphone_core_payload_type_enabled(lc,pt));
3818                 lp_config_set_string(lc->config,key,"recv_fmtp",pt->recv_fmtp);
3819                 index++;
3820         }
3821         sprintf(key,"video_codec_%i",index);
3822         lp_config_clean_section (lc->config,key);
3823         
3824         ms_list_free(lc->codecs_conf.audio_codecs);
3825         ms_list_free(lc->codecs_conf.video_codecs);
3826 }
3827
3828 void ui_config_uninit(LinphoneCore* lc)
3829 {
3830         if (lc->friends){
3831                 ms_list_for_each(lc->friends,(void (*)(void *))linphone_friend_destroy);
3832                 ms_list_free(lc->friends);
3833                 lc->friends=NULL;
3834         }
3835 }
3836
3837 /**
3838  * Returns the LpConfig object used to manage the storage (config) file.
3839  *
3840  * @ingroup misc
3841  * The application can use the LpConfig object to insert its own private 
3842  * sections and pairs of key=value in the configuration file.
3843  * 
3844 **/
3845 LpConfig *linphone_core_get_config(LinphoneCore *lc){
3846         return lc->config;
3847 }
3848
3849 static void linphone_core_uninit(LinphoneCore *lc)
3850 {
3851         linphone_core_free_hooks(lc);
3852         while(lc->calls)
3853         {
3854                 LinphoneCall *the_call = lc->calls->data;
3855                 linphone_core_terminate_call(lc,the_call);
3856                 linphone_core_iterate(lc);
3857 #ifdef WIN32
3858                 Sleep(50000);
3859 #else
3860                 usleep(50000);
3861 #endif
3862         }
3863         if (lc->friends)
3864                 ms_list_for_each(lc->friends,(void (*)(void *))linphone_friend_close_subscriptions);
3865         linphone_core_set_state(lc,LinphoneGlobalShutdown,"Shutting down");
3866 #ifdef VIDEO_ENABLED
3867         if (lc->previewstream!=NULL){
3868                 video_preview_stop(lc->previewstream);
3869                 lc->previewstream=NULL;
3870         }
3871 #endif
3872         ms_event_queue_destroy(lc->msevq);
3873         lc->msevq=NULL;
3874         /* save all config */
3875         net_config_uninit(lc);
3876         rtp_config_uninit(lc);
3877         if (lc->ringstream) ring_stop(lc->ringstream);
3878         sound_config_uninit(lc);
3879         video_config_uninit(lc);
3880         codecs_config_uninit(lc);
3881         ui_config_uninit(lc);
3882         sip_config_uninit(lc);
3883         if (lp_config_needs_commit(lc->config)) lp_config_sync(lc->config);
3884         lp_config_destroy(lc->config);
3885         lc->config = NULL; /* Mark the config as NULL to block further calls */
3886         sip_setup_unregister_all();
3887
3888         ms_list_for_each(lc->call_logs,(void (*)(void*))linphone_call_log_destroy);
3889         lc->call_logs=ms_list_free(lc->call_logs);
3890
3891         linphone_core_free_payload_types();
3892         ortp_exit();
3893         linphone_core_set_state(lc,LinphoneGlobalOff,"Off");
3894 }
3895
3896 static void set_network_reachable(LinphoneCore* lc,bool_t isReachable, time_t curtime){
3897         ms_message("Network state is now [%s]",isReachable?"UP":"DOWN");
3898         // second get the list of available proxies
3899         const MSList *elem=linphone_core_get_proxy_config_list(lc);
3900         for(;elem!=NULL;elem=elem->next){
3901                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
3902                 if (linphone_proxy_config_register_enabled(cfg) ) {
3903                         if (!isReachable) {
3904                                 cfg->registered=0;
3905                         }else{
3906                                 cfg->commit=TRUE;
3907                         }
3908                 }
3909         }
3910         lc->netup_time=curtime;
3911         lc->network_reachable=isReachable;
3912         if(!isReachable) {
3913                 sal_unlisten_ports (lc->sal);
3914         } else {
3915                 apply_transports(lc);
3916         }
3917
3918 }
3919 void linphone_core_refresh_registers(LinphoneCore* lc) {
3920         const MSList *elem=linphone_core_get_proxy_config_list(lc);
3921         for(;elem!=NULL;elem=elem->next){
3922                 LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)elem->data;
3923                 if (linphone_proxy_config_register_enabled(cfg) ) {
3924                         linphone_proxy_config_refresh_register(cfg);
3925                 }
3926         }
3927 }
3928
3929 void linphone_core_set_network_reachable(LinphoneCore* lc,bool_t isReachable) {
3930         //first disable automatic mode
3931         if (lc->auto_net_state_mon) {
3932                 ms_message("Disabling automatic network state monitoring");
3933                 lc->auto_net_state_mon=FALSE;
3934         }
3935         set_network_reachable(lc,isReachable, ms_time(NULL));
3936 }
3937
3938 bool_t linphone_core_is_network_reachabled(LinphoneCore* lc) {
3939         return lc->network_reachable;
3940 }
3941 ortp_socket_t linphone_core_get_sip_socket(LinphoneCore *lc){
3942         return sal_get_socket(lc->sal);
3943 }
3944 /**
3945  * Destroys a LinphoneCore
3946  *
3947  * @ingroup initializing
3948 **/
3949 void linphone_core_destroy(LinphoneCore *lc){
3950         linphone_core_uninit(lc);
3951         ms_free(lc);
3952 }
3953 /**
3954  * Get the number of Call
3955  *
3956  * @ingroup call_control
3957 **/
3958 int linphone_core_get_calls_nb(const LinphoneCore *lc){
3959         return  ms_list_size(lc->calls);;
3960 }
3961
3962 /**
3963  * Check if we do not have exceed the number of simultaneous call
3964  *
3965  * @ingroup call_control
3966 **/
3967 bool_t linphone_core_can_we_add_call(LinphoneCore *lc)
3968 {
3969         if(linphone_core_get_calls_nb(lc) < NB_MAX_CALLS)
3970                 return TRUE;
3971         ms_error("Maximum amount of simultaneous calls reached !");
3972         return FALSE;
3973 }
3974
3975
3976 int linphone_core_add_call( LinphoneCore *lc, LinphoneCall *call)
3977 {
3978         if(linphone_core_can_we_add_call(lc))
3979         {
3980                 lc->calls = ms_list_append(lc->calls,call);
3981                 return 0;
3982         }
3983         return -1;
3984 }
3985
3986 int linphone_core_del_call( LinphoneCore *lc, LinphoneCall *call)
3987 {
3988         MSList *it;
3989         MSList *the_calls = lc->calls;
3990         
3991         it=ms_list_find(the_calls,call);
3992         if (it) 
3993         {
3994                 the_calls = ms_list_remove_link(the_calls,it);
3995         }
3996         else
3997         {
3998                 ms_warning("could not find the call into the list\n");
3999                 return -1;
4000         }
4001         lc->calls = the_calls;
4002         return 0;
4003 }
4004
4005 /**
4006  * Specifiies a ring back tone to be played to far end during incoming calls.
4007 **/
4008 void linphone_core_set_remote_ringback_tone(LinphoneCore *lc, const char *file){
4009         if (lc->sound_conf.ringback_tone){
4010                 ms_free(lc->sound_conf.ringback_tone);
4011                 lc->sound_conf.ringback_tone=NULL;
4012         }
4013         if (file)
4014                 lc->sound_conf.ringback_tone=ms_strdup(file);
4015 }
4016
4017 /**
4018  * Returns the ring back tone played to far end during incoming calls.
4019 **/
4020 const char *linphone_core_get_remote_ringback_tone(const LinphoneCore *lc){
4021         return lc->sound_conf.ringback_tone;
4022 }
4023
4024 static PayloadType* find_payload_type_from_list(const char* type, int rate,const MSList* from) {
4025         const MSList *elem;
4026         for(elem=from;elem!=NULL;elem=elem->next){
4027                 PayloadType *pt=(PayloadType*)elem->data;
4028                 if ((strcmp((char*)type, payload_type_get_mime(pt)) == 0) && (rate == -1 || rate==pt->clock_rate)) {
4029                         return pt;
4030                 }
4031         }
4032         return NULL;
4033 }
4034
4035 /**
4036  * Get payload type  from mime type and clock rate
4037  * @ingroup media_parameters
4038  * This function searches in audio and video codecs for the given payload type name and clockrate.
4039  * Returns NULL if not found.
4040  */
4041 PayloadType* linphone_core_find_payload_type(LinphoneCore* lc, const char* type, int rate) {
4042         PayloadType* result = find_payload_type_from_list(type, rate, linphone_core_get_audio_codecs(lc));
4043         if (result)  {
4044                 return result;
4045         } else {
4046                 result = find_payload_type_from_list(type, rate, linphone_core_get_video_codecs(lc));
4047                 if (result) {
4048                         return result;
4049                 }
4050         }
4051         /*not found*/
4052         return NULL;
4053 }
4054
4055 const char *linphone_global_state_to_string(LinphoneGlobalState gs){
4056         switch(gs){
4057                 case LinphoneGlobalOff:
4058                         return "LinphoneGlobalOff";
4059                 break;
4060                 case LinphoneGlobalOn:
4061                         return "LinphoneGlobalOn";
4062                 break;
4063                 case LinphoneGlobalStartup:
4064                         return "LinphoneGlobalStartup";
4065                 break;
4066                 case LinphoneGlobalShutdown:
4067                         return "LinphoneGlobalShutdown";
4068                 break;
4069         }
4070         return NULL;
4071 }
4072
4073 LinphoneGlobalState linphone_core_get_global_state(const LinphoneCore *lc){
4074         return lc->state;
4075 }
4076
4077 LinphoneCallParams *linphone_core_create_default_call_parameters(LinphoneCore *lc){
4078         LinphoneCallParams *p=ms_new0(LinphoneCallParams,1);
4079         p->has_video=linphone_core_video_enabled(lc);
4080         return p;
4081 }
4082
4083 const char *linphone_error_to_string(LinphoneReason err){
4084         switch(err){
4085                 case LinphoneReasonNone:
4086                         return "No error";
4087                 case LinphoneReasonNoResponse:
4088                         return "No response";
4089                 case LinphoneReasonBadCredentials:
4090                         return "Bad credentials";
4091                 case LinphoneReasonDeclined:
4092                         return "Call declined";
4093         }
4094         return "unknown error";
4095 }
4096 /**
4097  * Enables signaling keep alive
4098  */
4099 void linphone_core_enable_keep_alive(LinphoneCore* lc,bool_t enable) {
4100         if (enable > 0) {
4101                 sal_set_keepalive_period(lc->sal,lc->sip_conf.keepalive_period);
4102         } else {
4103                 sal_set_keepalive_period(lc->sal,0);
4104         }
4105 }
4106 /**
4107  * Is signaling keep alive enabled
4108  */
4109 bool_t linphone_core_keep_alive_enabled(LinphoneCore* lc) {
4110         return sal_get_keepalive_period(lc->sal) > 0;
4111 }
4112         
4113 void linphone_core_start_dtmf_stream(LinphoneCore* lc) {
4114         get_dtmf_gen(lc); /*make sure ring stream is started*/
4115         lc->ringstream_autorelease=FALSE; /*disable autorelease mode*/
4116 }
4117
4118 void linphone_core_stop_dtmf_stream(LinphoneCore* lc) {
4119         if (lc->ringstream) ring_stop(lc->ringstream);
4120         lc->ringstream=NULL;
4121 }
4122
4123 typedef struct Hook{
4124         LinphoneCoreIterateHook fun;
4125         void *data;
4126 }Hook;
4127
4128 static Hook *hook_new(LinphoneCoreIterateHook hook, void *hook_data){
4129         Hook *h=ms_new(Hook,1);
4130         h->fun=hook;
4131         h->data=hook_data;
4132         return h;
4133 }
4134
4135 static void hook_invoke(Hook *h){
4136         h->fun(h->data);
4137 }
4138
4139 void linphone_core_add_iterate_hook(LinphoneCore *lc, LinphoneCoreIterateHook hook, void *hook_data){
4140         lc->hooks=ms_list_append(lc->hooks,hook_new(hook,hook_data));
4141 }
4142
4143 static void linphone_core_run_hooks(LinphoneCore *lc){
4144         ms_list_for_each(lc->hooks,(void (*)(void*))hook_invoke);
4145 }
4146
4147 static void linphone_core_free_hooks(LinphoneCore *lc){
4148         ms_list_for_each(lc->hooks,(void (*)(void*))ms_free);
4149         ms_list_free(lc->hooks);
4150         lc->hooks=NULL;
4151 }
4152
4153 void linphone_core_remove_iterate_hook(LinphoneCore *lc, LinphoneCoreIterateHook hook, void *hook_data){
4154         MSList *elem;
4155         for(elem=lc->hooks;elem!=NULL;elem=elem->next){
4156                 Hook *h=(Hook*)elem->data;
4157                 if (h->fun==hook && h->data==hook_data){
4158                         ms_list_remove_link(lc->hooks,elem);
4159                         ms_free(h);
4160                         return;
4161                 }
4162         }
4163         ms_error("linphone_core_remove_iterate_hook(): No such hook found.");
4164 }
4165
4166