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