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