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