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