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