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