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