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