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