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