]> sjero.net Git - linphone/blob - coreapi/linphonecall.c
fix contact address bug with ice
[linphone] / coreapi / linphonecall.c
1
2 /*
3 linphone
4 Copyright (C) 2010  Belledonne Communications SARL
5  (simon.morlat@linphone.org)
6
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License
9 as published by the Free Software Foundation; either version 2
10 of the License, or (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21 #ifdef WIN32
22 #include <time.h>
23 #endif
24 #include "linphonecore.h"
25 #include "sipsetup.h"
26 #include "lpconfig.h"
27 #include "private.h"
28 #include <ortp/event.h>
29 #include <ortp/b64.h>
30
31
32 #include "mediastreamer2/mediastream.h"
33 #include "mediastreamer2/msvolume.h"
34 #include "mediastreamer2/msequalizer.h"
35 #include "mediastreamer2/msfileplayer.h"
36 #include "mediastreamer2/msjpegwriter.h"
37 #include "mediastreamer2/mseventqueue.h"
38 #include "mediastreamer2/mssndcard.h"
39
40 #ifdef VIDEO_ENABLED
41 static MSWebCam *get_nowebcam_device(){
42         return ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),"StaticImage: Static picture");
43 }
44 #endif
45
46 static bool_t generate_b64_crypto_key(int key_length, char* key_out) {
47         int b64_size;
48         uint8_t* tmp = (uint8_t*) malloc(key_length);                   
49         if (ortp_crypto_get_random(tmp, key_length)!=0) {
50                 ms_error("Failed to generate random key");
51                 free(tmp);
52                 return FALSE;
53         }
54         
55         b64_size = b64_encode((const char*)tmp, key_length, NULL, 0);
56         if (b64_size == 0) {
57                 ms_error("Failed to b64 encode key");
58                 free(tmp);
59                 return FALSE;
60         }
61         key_out[b64_size] = '\0';
62         b64_encode((const char*)tmp, key_length, key_out, 40);
63         free(tmp);
64         return TRUE;
65 }
66
67 LinphoneCore *linphone_call_get_core(const LinphoneCall *call){
68         return call->core;
69 }
70
71 const char* linphone_call_get_authentication_token(LinphoneCall *call){
72         return call->auth_token;
73 }
74
75 bool_t linphone_call_get_authentication_token_verified(LinphoneCall *call){
76         return call->auth_token_verified;
77 }
78
79 static bool_t linphone_call_are_all_streams_encrypted(LinphoneCall *call) {
80         // Check ZRTP encryption in audiostream
81         if (!call->audiostream_encrypted) {
82                 return FALSE;
83         }
84
85 #ifdef VIDEO_ENABLED
86         // If video enabled, check ZRTP encryption in videostream
87         const LinphoneCallParams *params=linphone_call_get_current_params(call);
88         if (params->has_video && !call->videostream_encrypted) {
89                 return FALSE;
90         }
91 #endif
92
93         return TRUE;
94 }
95
96 void propagate_encryption_changed(LinphoneCall *call){
97         LinphoneCore *lc=call->core;
98         if (!linphone_call_are_all_streams_encrypted(call)) {
99                 ms_message("Some streams are not encrypted");
100                 call->current_params.media_encryption=LinphoneMediaEncryptionNone;
101                 if (lc->vtable.call_encryption_changed)
102                         lc->vtable.call_encryption_changed(call->core, call, FALSE, call->auth_token);
103         } else {
104                 ms_message("All streams are encrypted");
105                 call->current_params.media_encryption=LinphoneMediaEncryptionZRTP;
106                 if (lc->vtable.call_encryption_changed)
107                         lc->vtable.call_encryption_changed(call->core, call, TRUE, call->auth_token);
108         }
109 }
110
111 #ifdef VIDEO_ENABLED
112 static void linphone_call_videostream_encryption_changed(void *data, bool_t encrypted){
113         ms_message("Video stream is %s", encrypted ? "encrypted" : "not encrypted");
114
115         LinphoneCall *call = (LinphoneCall *)data;
116         call->videostream_encrypted=encrypted;
117         propagate_encryption_changed(call);
118 }
119 #endif
120
121 static void linphone_call_audiostream_encryption_changed(void *data, bool_t encrypted) {
122         char status[255]={0};
123         ms_message("Audio stream is %s ", encrypted ? "encrypted" : "not encrypted");
124
125         LinphoneCall *call = (LinphoneCall *)data;
126         call->audiostream_encrypted=encrypted;
127         
128         if (encrypted && call->core->vtable.display_status != NULL) {
129                 snprintf(status,sizeof(status)-1,_("Authentication token is %s"),call->auth_token);
130                  call->core->vtable.display_status(call->core, status);
131         }
132
133         propagate_encryption_changed(call);
134
135
136 #ifdef VIDEO_ENABLED
137         // Enable video encryption
138         const LinphoneCallParams *params=linphone_call_get_current_params(call);
139         if (params->has_video) {
140                 ms_message("Trying to enable encryption on video stream");
141                 OrtpZrtpParams params;
142                 params.zid_file=NULL; //unused
143                 video_stream_enable_zrtp(call->videostream,call->audiostream,&params);
144         }
145 #endif
146 }
147
148
149 static void linphone_call_audiostream_auth_token_ready(void *data, const char* auth_token, bool_t verified) {
150         LinphoneCall *call=(LinphoneCall *)data;
151         if (call->auth_token != NULL)
152                 ms_free(call->auth_token);
153
154         call->auth_token=ms_strdup(auth_token);
155         call->auth_token_verified=verified;
156
157         ms_message("Authentication token is %s (%s)", auth_token, verified?"verified":"unverified");
158 }
159
160 void linphone_call_set_authentication_token_verified(LinphoneCall *call, bool_t verified){
161         if (call->audiostream==NULL){
162                 ms_error("linphone_call_set_authentication_token_verified(): No audio stream");
163         }
164         if (call->audiostream->ortpZrtpContext==NULL){
165                 ms_error("linphone_call_set_authentication_token_verified(): No zrtp context.");
166         }
167         if (!call->auth_token_verified && verified){
168                 ortp_zrtp_sas_verified(call->audiostream->ortpZrtpContext);
169         }else if (call->auth_token_verified && !verified){
170                 ortp_zrtp_sas_reset_verified(call->audiostream->ortpZrtpContext);
171         }
172         call->auth_token_verified=verified;
173         propagate_encryption_changed(call);
174 }
175
176 static MSList *make_codec_list(LinphoneCore *lc, const MSList *codecs, int bandwidth_limit,int* max_sample_rate){
177         MSList *l=NULL;
178         const MSList *it;
179         if (max_sample_rate) *max_sample_rate=0;
180         for(it=codecs;it!=NULL;it=it->next){
181                 PayloadType *pt=(PayloadType*)it->data;
182                 if (pt->flags & PAYLOAD_TYPE_ENABLED){
183                         if (bandwidth_limit>0 && !linphone_core_is_payload_type_usable_for_bandwidth(lc,pt,bandwidth_limit)){
184                                 ms_message("Codec %s/%i eliminated because of audio bandwidth constraint.",pt->mime_type,pt->clock_rate);
185                                 continue;
186                         }
187                         if (linphone_core_check_payload_type_usability(lc,pt)){
188                                 l=ms_list_append(l,payload_type_clone(pt));
189                                 if (max_sample_rate && payload_type_get_rate(pt)>*max_sample_rate) *max_sample_rate=payload_type_get_rate(pt);
190                         }
191                 }
192         }
193         return l;
194 }
195
196 static void update_media_description_from_stun(SalMediaDescription *md, const StunCandidate *ac, const StunCandidate *vc){
197         if (ac->port!=0){
198                 strcpy(md->streams[0].rtp_addr,ac->addr);
199                 md->streams[0].rtp_port=ac->port;
200                 if ((ac->addr[0]!='\0' && vc->addr[0]!='\0' && strcmp(ac->addr,vc->addr)==0) || md->nstreams==1){
201                         strcpy(md->addr,ac->addr);
202                 }
203         }
204         if (vc->port!=0){
205                 strcpy(md->streams[1].rtp_addr,vc->addr);
206                 md->streams[1].rtp_port=vc->port;
207         }
208         
209 }
210
211
212 static SalMediaDescription *_create_local_media_description(LinphoneCore *lc, LinphoneCall *call, unsigned int session_id, unsigned int session_ver){
213         MSList *l;
214         PayloadType *pt;
215         int i;
216         const char *me=linphone_core_get_identity(lc);
217         LinphoneAddress *addr=linphone_address_new(me);
218         const char *username=linphone_address_get_username (addr);
219         SalMediaDescription *md=sal_media_description_new();
220         
221         if (call->ping_time>0) {
222                 linphone_core_adapt_to_network(lc,call->ping_time,&call->params);
223         }
224
225         md->session_id=session_id;
226         md->session_ver=session_ver;
227         md->nstreams=1;
228         strncpy(md->addr,call->localip,sizeof(md->addr));
229         strncpy(md->username,username,sizeof(md->username));
230         
231         if (call->params.down_bw)
232                 md->bandwidth=call->params.down_bw;
233         else md->bandwidth=linphone_core_get_download_bandwidth(lc);
234
235         /*set audio capabilities */
236         strncpy(md->streams[0].rtp_addr,call->localip,sizeof(md->streams[0].rtp_addr));
237         strncpy(md->streams[0].rtcp_addr,call->localip,sizeof(md->streams[0].rtcp_addr));
238         md->streams[0].rtp_port=call->audio_port;
239         md->streams[0].rtcp_port=call->audio_port+1;
240         md->streams[0].proto=(call->params.media_encryption == LinphoneMediaEncryptionSRTP) ? 
241                 SalProtoRtpSavp : SalProtoRtpAvp;
242         md->streams[0].type=SalAudio;
243         if (call->params.down_ptime)
244                 md->streams[0].ptime=call->params.down_ptime;
245         else
246                 md->streams[0].ptime=linphone_core_get_download_ptime(lc);
247         l=make_codec_list(lc,lc->codecs_conf.audio_codecs,call->params.audio_bw,&md->streams[0].max_rate);
248         pt=payload_type_clone(rtp_profile_get_payload_from_mime(&av_profile,"telephone-event"));
249         l=ms_list_append(l,pt);
250         md->streams[0].payloads=l;
251         
252
253
254         if (call->params.has_video){
255                 md->nstreams++;
256                 md->streams[1].rtp_port=call->video_port;
257                 md->streams[1].rtcp_port=call->video_port+1;
258                 md->streams[1].proto=md->streams[0].proto;
259                 md->streams[1].type=SalVideo;
260                 l=make_codec_list(lc,lc->codecs_conf.video_codecs,0,NULL);
261                 md->streams[1].payloads=l;
262         }
263         
264         for(i=0; i<md->nstreams; i++) {
265                 if (md->streams[i].proto == SalProtoRtpSavp) {
266                         md->streams[i].crypto[0].tag = 1;
267                         md->streams[i].crypto[0].algo = AES_128_SHA1_80;
268                         if (!generate_b64_crypto_key(30, md->streams[i].crypto[0].master_key))
269                                 md->streams[i].crypto[0].algo = 0;
270                         md->streams[i].crypto[1].tag = 2;
271                         md->streams[i].crypto[1].algo = AES_128_SHA1_32;
272                         if (!generate_b64_crypto_key(30, md->streams[i].crypto[1].master_key))
273                                 md->streams[i].crypto[1].algo = 0;
274                         md->streams[i].crypto[2].algo = 0;
275                 }
276         }
277         update_media_description_from_stun(md,&call->ac,&call->vc);
278         if (call->ice_session != NULL) {
279                 linphone_core_update_local_media_description_from_ice(md, call->ice_session);
280         }
281         linphone_address_destroy(addr);
282         return md;
283 }
284
285 void update_local_media_description(LinphoneCore *lc, LinphoneCall *call){
286         SalMediaDescription *md=call->localdesc;
287         if (md== NULL) {
288                 call->localdesc = create_local_media_description(lc,call);
289         } else {
290                 call->localdesc = _create_local_media_description(lc,call,md->session_id,md->session_ver+1);
291                 sal_media_description_unref(md);
292         }
293 }
294
295 SalMediaDescription *create_local_media_description(LinphoneCore *lc, LinphoneCall *call){
296         unsigned int id=rand() & 0xfff;
297         return _create_local_media_description(lc,call,id,id);
298 }
299
300 static int find_port_offset(LinphoneCore *lc){
301         int offset;
302         MSList *elem;
303         int audio_port;
304         bool_t already_used=FALSE;
305         for(offset=0;offset<100;offset+=2){
306                 audio_port=linphone_core_get_audio_port (lc)+offset;
307                 already_used=FALSE;
308                 for(elem=lc->calls;elem!=NULL;elem=elem->next){
309                         LinphoneCall *call=(LinphoneCall*)elem->data;
310                         if (call->audio_port==audio_port) {
311                                 already_used=TRUE;
312                                 break;
313                         }
314                 }
315                 if (!already_used) break;
316         }
317         if (offset==100){
318                 ms_error("Could not find any free port !");
319                 return -1;
320         }
321         return offset;
322 }
323
324 static void linphone_call_init_common(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
325         int port_offset;
326         call->magic=linphone_call_magic;
327         call->refcnt=1;
328         call->state=LinphoneCallIdle;
329         call->transfer_state = LinphoneCallIdle;
330         call->start_time=time(NULL);
331         call->media_start_time=0;
332         call->log=linphone_call_log_new(call, from, to);
333         call->owns_call_log=TRUE;
334         linphone_core_notify_all_friends(call->core,LinphoneStatusOnThePhone);
335         port_offset=find_port_offset (call->core);
336         if (port_offset==-1) return;
337         call->audio_port=linphone_core_get_audio_port(call->core)+port_offset;
338         call->video_port=linphone_core_get_video_port(call->core)+port_offset;
339         linphone_call_init_stats(&call->stats[LINPHONE_CALL_STATS_AUDIO], LINPHONE_CALL_STATS_AUDIO);
340         linphone_call_init_stats(&call->stats[LINPHONE_CALL_STATS_VIDEO], LINPHONE_CALL_STATS_VIDEO);
341 }
342
343 void linphone_call_init_stats(LinphoneCallStats *stats, int type) {
344         stats->type = type;
345         stats->received_rtcp = NULL;
346         stats->sent_rtcp = NULL;
347         stats->ice_state = LinphoneIceStateNotActivated;
348 }
349
350
351 static void discover_mtu(LinphoneCore *lc, const char *remote){
352         int mtu;
353         if (lc->net_conf.mtu==0 ){
354                 /*attempt to discover mtu*/
355                 mtu=ms_discover_mtu(remote);
356                 if (mtu>0){
357                         ms_set_mtu(mtu);
358                         ms_message("Discovered mtu is %i, RTP payload max size is %i",
359                                 mtu, ms_get_payload_max_size());
360                 }
361         }
362 }
363
364 LinphoneCall * linphone_call_new_outgoing(struct _LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, const LinphoneCallParams *params)
365 {
366         LinphoneCall *call=ms_new0(LinphoneCall,1);
367         call->dir=LinphoneCallOutgoing;
368         call->op=sal_op_new(lc->sal);
369         sal_op_set_user_pointer(call->op,call);
370         call->core=lc;
371         linphone_core_get_local_ip(lc,linphone_address_get_domain(to),call->localip);
372         linphone_call_init_common(call,from,to);
373         call->params=*params;
374         if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseIce) {
375                 call->ice_session = ice_session_new();
376                 ice_session_set_role(call->ice_session, IR_Controlling);
377         }
378         if (linphone_core_get_firewall_policy(call->core) == LinphonePolicyUseStun) {
379                 call->ping_time=linphone_core_run_stun_tests(call->core,call);
380         }
381         call->camera_active=params->has_video;
382         
383         discover_mtu(lc,linphone_address_get_domain (to));
384         if (params->referer){
385                 sal_call_set_referer(call->op,params->referer->op);
386                 call->referer=linphone_call_ref(params->referer);
387         }
388         return call;
389 }
390
391 LinphoneCall * linphone_call_new_incoming(LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, SalOp *op){
392         LinphoneCall *call=ms_new0(LinphoneCall,1);
393         char *from_str;
394
395         call->dir=LinphoneCallIncoming;
396         sal_op_set_user_pointer(op,call);
397         call->op=op;
398         call->core=lc;
399
400         if (lc->sip_conf.ping_with_options){
401                 /*the following sends an option request back to the caller so that
402                  we get a chance to discover our nat'd address before answering.*/
403                 call->ping_op=sal_op_new(lc->sal);
404                 from_str=linphone_address_as_string_uri_only(from);
405                 sal_op_set_route(call->ping_op,sal_op_get_network_origin(op));
406                 sal_op_set_user_pointer(call->ping_op,call);
407                 sal_ping(call->ping_op,linphone_core_find_best_identity(lc,from,NULL),from_str);
408                 ms_free(from_str);
409         }
410
411         linphone_address_clean(from);
412         linphone_core_get_local_ip(lc,linphone_address_get_domain(from),call->localip);
413         linphone_call_init_common(call, from, to);
414         linphone_core_init_default_params(lc, &call->params);
415         call->params.has_video &= !!lc->video_policy.automatically_accept;
416         switch (linphone_core_get_firewall_policy(call->core)) {
417                 case LinphonePolicyUseIce:
418                         call->ice_session = ice_session_new();
419                         ice_session_set_role(call->ice_session, IR_Controlled);
420                         linphone_core_update_ice_from_remote_media_description(call, sal_call_get_remote_media_description(op));
421                         if (call->ice_session != NULL) {
422                                 linphone_call_init_media_streams(call);
423                                 linphone_call_start_media_streams_for_ice_gathering(call);
424                                 if (linphone_core_gather_ice_candidates(call->core,call)<0) {
425                                         /* Ice candidates gathering failed, proceed with the call anyway. */
426                                         linphone_call_delete_ice_session(call);
427                                         linphone_call_stop_media_streams(call);
428                                 }
429                         }
430                         break;
431                 case LinphonePolicyUseStun:
432                         call->ping_time=linphone_core_run_stun_tests(call->core,call);
433                         /* No break to also destroy ice session in this case. */
434                 default:
435                         break;
436         }
437         call->camera_active=call->params.has_video;
438         
439         discover_mtu(lc,linphone_address_get_domain(from));
440         return call;
441 }
442
443 /* this function is called internally to get rid of a call.
444  It performs the following tasks:
445  - remove the call from the internal list of calls
446  - update the call logs accordingly
447 */
448
449 static void linphone_call_set_terminated(LinphoneCall *call){
450         LinphoneCore *lc=call->core;
451
452         linphone_core_update_allocated_audio_bandwidth(lc);
453
454         call->owns_call_log=FALSE;
455         linphone_call_log_completed(call);
456
457
458         if (call == lc->current_call){
459                 ms_message("Resetting the current call");
460                 lc->current_call=NULL;
461         }
462
463         if (linphone_core_del_call(lc,call) != 0){
464                 ms_error("Could not remove the call from the list !!!");
465         }
466
467         if (ms_list_size(lc->calls)==0)
468                 linphone_core_notify_all_friends(lc,lc->presence_mode);
469
470         linphone_core_conference_check_uninit(lc);
471         if (call->ringing_beep){
472                 linphone_core_stop_dtmf(lc);
473                 call->ringing_beep=FALSE;
474         }
475         if (call->referer){
476                 linphone_call_unref(call->referer);
477                 call->referer=NULL;
478         }
479 }
480
481 void linphone_call_fix_call_parameters(LinphoneCall *call){
482         call->params.has_video=call->current_params.has_video;
483         call->params.media_encryption=call->current_params.media_encryption;
484 }
485
486 const char *linphone_call_state_to_string(LinphoneCallState cs){
487         switch (cs){
488                 case LinphoneCallIdle:
489                         return "LinphoneCallIdle";
490                 case LinphoneCallIncomingReceived:
491                         return "LinphoneCallIncomingReceived";
492                 case LinphoneCallOutgoingInit:
493                         return "LinphoneCallOutgoingInit";
494                 case LinphoneCallOutgoingProgress:
495                         return "LinphoneCallOutgoingProgress";
496                 case LinphoneCallOutgoingRinging:
497                         return "LinphoneCallOutgoingRinging";
498                 case LinphoneCallOutgoingEarlyMedia:
499                         return "LinphoneCallOutgoingEarlyMedia";
500                 case LinphoneCallConnected:
501                         return "LinphoneCallConnected";
502                 case LinphoneCallStreamsRunning:
503                         return "LinphoneCallStreamsRunning";
504                 case LinphoneCallPausing:
505                         return "LinphoneCallPausing";
506                 case LinphoneCallPaused:
507                         return "LinphoneCallPaused";
508                 case LinphoneCallResuming:
509                         return "LinphoneCallResuming";
510                 case LinphoneCallRefered:
511                         return "LinphoneCallRefered";
512                 case LinphoneCallError:
513                         return "LinphoneCallError";
514                 case LinphoneCallEnd:
515                         return "LinphoneCallEnd";
516                 case LinphoneCallPausedByRemote:
517                         return "LinphoneCallPausedByRemote";
518                 case LinphoneCallUpdatedByRemote:
519                         return "LinphoneCallUpdatedByRemote";
520                 case LinphoneCallIncomingEarlyMedia:
521                         return "LinphoneCallIncomingEarlyMedia";
522                 case LinphoneCallUpdated:
523                         return "LinphoneCallUpdated";
524                 case LinphoneCallReleased:
525                         return "LinphoneCallReleased";
526         }
527         return "undefined state";
528 }
529
530 void linphone_call_set_state(LinphoneCall *call, LinphoneCallState cstate, const char *message){
531         LinphoneCore *lc=call->core;
532
533         if (call->state!=cstate){
534                 if (call->state==LinphoneCallEnd || call->state==LinphoneCallError){
535                         if (cstate!=LinphoneCallReleased){
536                                 ms_warning("Spurious call state change from %s to %s, ignored.",linphone_call_state_to_string(call->state),
537                                    linphone_call_state_to_string(cstate));
538                                 return;
539                         }
540                 }
541                 ms_message("Call %p: moving from state %s to %s",call,linphone_call_state_to_string(call->state),
542                            linphone_call_state_to_string(cstate));
543                 if (cstate!=LinphoneCallRefered){
544                         /*LinphoneCallRefered is rather an event, not a state.
545                          Indeed it does not change the state of the call (still paused or running)*/
546                         call->state=cstate;
547                 }
548                 if (cstate==LinphoneCallEnd || cstate==LinphoneCallError){
549                         switch(call->reason){
550                                 case LinphoneReasonDeclined:
551                                         call->log->status=LinphoneCallDeclined;
552                                         break;
553                                 case LinphoneReasonNotAnswered:
554                                         call->log->status=LinphoneCallMissed;
555                                 break;
556                                 default:
557                                 break;
558                         }
559                         linphone_call_set_terminated (call);
560                 }
561                 if (cstate == LinphoneCallConnected) {
562                         call->log->status=LinphoneCallSuccess;
563                         call->media_start_time=time(NULL);
564                 }
565
566                 if (lc->vtable.call_state_changed)
567                         lc->vtable.call_state_changed(lc,call,cstate,message);
568                 if (cstate==LinphoneCallReleased){
569                         if (call->op!=NULL) {
570                                 /* so that we cannot have anymore upcalls for SAL
571                                  concerning this call*/
572                                 sal_op_release(call->op);
573                                 call->op=NULL;
574                         }
575                         linphone_call_unref(call);
576                 }
577         }
578 }
579
580 static void linphone_call_destroy(LinphoneCall *obj)
581 {
582         if (obj->op!=NULL) {
583                 sal_op_release(obj->op);
584                 obj->op=NULL;
585         }
586         if (obj->resultdesc!=NULL) {
587                 sal_media_description_unref(obj->resultdesc);
588                 obj->resultdesc=NULL;
589         }
590         if (obj->localdesc!=NULL) {
591                 sal_media_description_unref(obj->localdesc);
592                 obj->localdesc=NULL;
593         }
594         if (obj->ping_op) {
595                 sal_op_release(obj->ping_op);
596         }
597         if (obj->refer_to){
598                 ms_free(obj->refer_to);
599         }
600         if (obj->owns_call_log)
601                 linphone_call_log_destroy(obj->log);
602         if (obj->auth_token) {
603                 ms_free(obj->auth_token);
604         }
605         if (obj->ice_session) {
606                 ice_session_destroy(obj->ice_session);
607         }
608
609         ms_free(obj);
610 }
611
612 /**
613  * @addtogroup call_control
614  * @{
615 **/
616
617 /**
618  * Increments the call 's reference count.
619  * An application that wishes to retain a pointer to call object
620  * must use this function to unsure the pointer remains
621  * valid. Once the application no more needs this pointer,
622  * it must call linphone_call_unref().
623 **/
624 LinphoneCall * linphone_call_ref(LinphoneCall *obj){
625         obj->refcnt++;
626         return obj;
627 }
628
629 /**
630  * Decrements the call object reference count.
631  * See linphone_call_ref().
632 **/
633 void linphone_call_unref(LinphoneCall *obj){
634         obj->refcnt--;
635         if (obj->refcnt==0){
636                 linphone_call_destroy(obj);
637         }
638 }
639
640 /**
641  * Returns current parameters associated to the call.
642 **/
643 const LinphoneCallParams * linphone_call_get_current_params(const LinphoneCall *call){
644         return &call->current_params;
645 }
646
647 static bool_t is_video_active(const SalStreamDescription *sd){
648         return sd->rtp_port!=0 && sd->dir!=SalStreamInactive;
649 }
650
651 /**
652  * Returns call parameters proposed by remote.
653  * 
654  * This is useful when receiving an incoming call, to know whether the remote party
655  * supports video, encryption or whatever.
656 **/
657 const LinphoneCallParams * linphone_call_get_remote_params(LinphoneCall *call){
658         LinphoneCallParams *cp=&call->remote_params;
659         memset(cp,0,sizeof(*cp));
660         if (call->op){
661                 SalMediaDescription *md=sal_call_get_remote_media_description(call->op);
662                 if (md){
663                         SalStreamDescription *asd,*vsd,*secure_asd,*secure_vsd;
664
665                         asd=sal_media_description_find_stream(md,SalProtoRtpAvp,SalAudio);
666                         vsd=sal_media_description_find_stream(md,SalProtoRtpAvp,SalVideo);
667                         secure_asd=sal_media_description_find_stream(md,SalProtoRtpSavp,SalAudio);
668                         secure_vsd=sal_media_description_find_stream(md,SalProtoRtpSavp,SalVideo);
669                         if (secure_vsd){
670                                 cp->has_video=is_video_active(secure_vsd);
671                                 if (secure_asd || asd==NULL)
672                                         cp->media_encryption=LinphoneMediaEncryptionSRTP;
673                         }else if (vsd){
674                                 cp->has_video=is_video_active(vsd);
675                         }
676                         return cp;
677                 }
678         }
679         return NULL;
680 }
681
682 /**
683  * Returns the remote address associated to this call
684  *
685 **/
686 const LinphoneAddress * linphone_call_get_remote_address(const LinphoneCall *call){
687         return call->dir==LinphoneCallIncoming ? call->log->from : call->log->to;
688 }
689
690 /**
691  * Returns the remote address associated to this call as a string.
692  *
693  * The result string must be freed by user using ms_free().
694 **/
695 char *linphone_call_get_remote_address_as_string(const LinphoneCall *call){
696         return linphone_address_as_string(linphone_call_get_remote_address(call));
697 }
698
699 /**
700  * Retrieves the call's current state.
701 **/
702 LinphoneCallState linphone_call_get_state(const LinphoneCall *call){
703         return call->state;
704 }
705
706 /**
707  * Returns the reason for a call termination (either error or normal termination)
708 **/
709 LinphoneReason linphone_call_get_reason(const LinphoneCall *call){
710         return call->reason;
711 }
712
713 /**
714  * Get the user_pointer in the LinphoneCall
715  *
716  * @ingroup call_control
717  *
718  * return user_pointer an opaque user pointer that can be retrieved at any time
719 **/
720 void *linphone_call_get_user_pointer(LinphoneCall *call)
721 {
722         return call->user_pointer;
723 }
724
725 /**
726  * Set the user_pointer in the LinphoneCall
727  *
728  * @ingroup call_control
729  *
730  * the user_pointer is an opaque user pointer that can be retrieved at any time in the LinphoneCall
731 **/
732 void linphone_call_set_user_pointer(LinphoneCall *call, void *user_pointer)
733 {
734         call->user_pointer = user_pointer;
735 }
736
737 /**
738  * Returns the call log associated to this call.
739 **/
740 LinphoneCallLog *linphone_call_get_call_log(const LinphoneCall *call){
741         return call->log;
742 }
743
744 /**
745  * Returns the refer-to uri (if the call was transfered).
746 **/
747 const char *linphone_call_get_refer_to(const LinphoneCall *call){
748         return call->refer_to;
749 }
750
751 /**
752  * Returns direction of the call (incoming or outgoing).
753 **/
754 LinphoneCallDir linphone_call_get_dir(const LinphoneCall *call){
755         return call->log->dir;
756 }
757
758 /**
759  * Returns the far end's user agent description string, if available.
760 **/
761 const char *linphone_call_get_remote_user_agent(LinphoneCall *call){
762         if (call->op){
763                 return sal_op_get_remote_ua (call->op);
764         }
765         return NULL;
766 }
767
768 /**
769  * Returns true if this calls has received a transfer that has not been
770  * executed yet.
771  * Pending transfers are executed when this call is being paused or closed,
772  * locally or by remote endpoint.
773  * If the call is already paused while receiving the transfer request, the
774  * transfer immediately occurs.
775 **/
776 bool_t linphone_call_has_transfer_pending(const LinphoneCall *call){
777         return call->refer_pending;
778 }
779
780 /**
781  * Returns call's duration in seconds.
782 **/
783 int linphone_call_get_duration(const LinphoneCall *call){
784         if (call->media_start_time==0) return 0;
785         return time(NULL)-call->media_start_time;
786 }
787
788 /**
789  * Returns the call object this call is replacing, if any.
790  * Call replacement can occur during call transfers.
791  * By default, the core automatically terminates the replaced call and accept the new one.
792  * This function allows the application to know whether a new incoming call is a one that replaces another one.
793 **/
794 LinphoneCall *linphone_call_get_replaced_call(LinphoneCall *call){
795         SalOp *op=sal_call_get_replaces(call->op);
796         if (op){
797                 return (LinphoneCall*)sal_op_get_user_pointer(op);
798         }
799         return NULL;
800 }
801
802 /**
803  * Indicate whether camera input should be sent to remote end.
804 **/
805 void linphone_call_enable_camera (LinphoneCall *call, bool_t enable){
806 #ifdef VIDEO_ENABLED
807         if (call->videostream!=NULL && call->videostream->ticker!=NULL){
808                 LinphoneCore *lc=call->core;
809                 MSWebCam *nowebcam=get_nowebcam_device();
810                 if (call->camera_active!=enable && lc->video_conf.device!=nowebcam){
811                         video_stream_change_camera(call->videostream,
812                                      enable ? lc->video_conf.device : nowebcam);
813                 }
814         }
815         call->camera_active=enable;
816 #endif
817 }
818
819 /**
820  * Take a photo of currently received video and write it into a jpeg file.
821 **/
822 int linphone_call_take_video_snapshot(LinphoneCall *call, const char *file){
823 #ifdef VIDEO_ENABLED
824         if (call->videostream!=NULL && call->videostream->jpegwriter!=NULL){
825                 return ms_filter_call_method(call->videostream->jpegwriter,MS_JPEG_WRITER_TAKE_SNAPSHOT,(void*)file);
826         }
827         ms_warning("Cannot take snapshot: no currently running video stream on this call.");
828         return -1;
829 #endif
830         return -1;
831 }
832
833 /**
834  * Returns TRUE if camera pictures are sent to the remote party.
835 **/
836 bool_t linphone_call_camera_enabled (const LinphoneCall *call){
837         return call->camera_active;
838 }
839
840 /**
841  * Enable video stream.
842 **/
843 void linphone_call_params_enable_video(LinphoneCallParams *cp, bool_t enabled){
844         cp->has_video=enabled;
845 }
846
847 const PayloadType* linphone_call_params_get_used_audio_codec(const LinphoneCallParams *cp) {
848         return cp->audio_codec;
849 }
850
851 const PayloadType* linphone_call_params_get_used_video_codec(const LinphoneCallParams *cp) {
852         return cp->video_codec;
853 }
854
855 /**
856  * Returns whether video is enabled.
857 **/
858 bool_t linphone_call_params_video_enabled(const LinphoneCallParams *cp){
859         return cp->has_video;
860 }
861
862 enum LinphoneMediaEncryption linphone_call_params_get_media_encryption(const LinphoneCallParams *cp) {
863         return cp->media_encryption;
864 }
865
866 void linphone_call_params_set_media_encryption(LinphoneCallParams *cp, enum LinphoneMediaEncryption e) {
867         cp->media_encryption = e;
868 }
869
870
871 /**
872  * Enable sending of real early media (during outgoing calls).
873 **/
874 void linphone_call_params_enable_early_media_sending(LinphoneCallParams *cp, bool_t enabled){
875         cp->real_early_media=enabled;
876 }
877
878 bool_t linphone_call_params_early_media_sending_enabled(const LinphoneCallParams *cp){
879         return cp->real_early_media;
880 }
881
882 /**
883  * Returns true if the call is part of the locally managed conference.
884 **/
885 bool_t linphone_call_params_local_conference_mode(const LinphoneCallParams *cp){
886         return cp->in_conference;
887 }
888
889 /**
890  * Refine bandwidth settings for this call by setting a bandwidth limit for audio streams.
891  * As a consequence, codecs whose bitrates are not compatible with this limit won't be used.
892 **/
893 void linphone_call_params_set_audio_bandwidth_limit(LinphoneCallParams *cp, int bandwidth){
894         cp->audio_bw=bandwidth;
895 }
896
897 #ifdef VIDEO_ENABLED
898 /**
899  * Request remote side to send us a Video Fast Update.
900 **/
901 void linphone_call_send_vfu_request(LinphoneCall *call)
902 {
903         if (LinphoneCallStreamsRunning == linphone_call_get_state(call))
904                 sal_call_send_vfu_request(call->op);
905 }
906 #endif
907
908 /**
909  *
910 **/
911 LinphoneCallParams * linphone_call_params_copy(const LinphoneCallParams *cp){
912         LinphoneCallParams *ncp=ms_new0(LinphoneCallParams,1);
913         memcpy(ncp,cp,sizeof(LinphoneCallParams));
914         return ncp;
915 }
916
917 /**
918  *
919 **/
920 void linphone_call_params_destroy(LinphoneCallParams *p){
921         ms_free(p);
922 }
923
924 /**
925  * @}
926 **/
927
928
929 #ifdef TEST_EXT_RENDERER
930 static void rendercb(void *data, const MSPicture *local, const MSPicture *remote){
931         ms_message("rendercb, local buffer=%p, remote buffer=%p",
932                    local ? local->planes[0] : NULL, remote? remote->planes[0] : NULL);
933 }
934 #endif
935
936 #ifdef VIDEO_ENABLED
937 static void video_stream_event_cb(void *user_pointer, const MSFilter *f, const unsigned int event_id, const void *args){
938     LinphoneCall* call = (LinphoneCall*) user_pointer;
939         ms_warning("In linphonecall.c: video_stream_event_cb");
940         switch (event_id) {
941                 case MS_VIDEO_DECODER_DECODING_ERRORS:
942                         ms_warning("Case is MS_VIDEO_DECODER_DECODING_ERRORS");
943                         linphone_call_send_vfu_request(call);
944                         break;
945         case MS_VIDEO_DECODER_FIRST_IMAGE_DECODED:
946             ms_message("First video frame decoded successfully");
947             if (call->nextVideoFrameDecoded._func != NULL)
948                 call->nextVideoFrameDecoded._func(call, call->nextVideoFrameDecoded._user_data);
949             break;
950                 default:
951                         ms_warning("Unhandled event %i", event_id);
952                         break;
953         }
954 }
955 #endif
956
957 void linphone_call_set_next_video_frame_decoded_callback(LinphoneCall *call, LinphoneCallCbFunc cb, void* user_data) {
958     call->nextVideoFrameDecoded._func = cb;
959     call->nextVideoFrameDecoded._user_data = user_data;
960 #ifdef VIDEO_ENABLED
961     ms_filter_call_method_noarg(call->videostream->decoder, MS_VIDEO_DECODER_RESET_FIRST_IMAGE_NOTIFICATION);
962 #endif
963 }
964
965 void linphone_call_init_audio_stream(LinphoneCall *call){
966         LinphoneCore *lc=call->core;
967         AudioStream *audiostream;
968         int dscp=linphone_core_get_audio_dscp(lc);
969
970         call->audiostream=audiostream=audio_stream_new(call->audio_port,call->audio_port+1,linphone_core_ipv6_enabled(lc));
971         if (dscp!=-1)
972                 audio_stream_set_dscp(audiostream,dscp);
973         if (linphone_core_echo_limiter_enabled(lc)){
974                 const char *type=lp_config_get_string(lc->config,"sound","el_type","mic");
975                 if (strcasecmp(type,"mic")==0)
976                         audio_stream_enable_echo_limiter(audiostream,ELControlMic);
977                 else if (strcasecmp(type,"full")==0)
978                         audio_stream_enable_echo_limiter(audiostream,ELControlFull);
979         }
980         audio_stream_enable_gain_control(audiostream,TRUE);
981         if (linphone_core_echo_cancellation_enabled(lc)){
982                 int len,delay,framesize;
983                 const char *statestr=lp_config_get_string(lc->config,"sound","ec_state",NULL);
984                 len=lp_config_get_int(lc->config,"sound","ec_tail_len",0);
985                 delay=lp_config_get_int(lc->config,"sound","ec_delay",0);
986                 framesize=lp_config_get_int(lc->config,"sound","ec_framesize",0);
987                 audio_stream_set_echo_canceller_params(audiostream,len,delay,framesize);
988                 if (statestr && audiostream->ec){
989                         ms_filter_call_method(audiostream->ec,MS_ECHO_CANCELLER_SET_STATE_STRING,(void*)statestr);
990                 }
991         }
992         audio_stream_enable_automatic_gain_control(audiostream,linphone_core_agc_enabled(lc));
993         {
994                 int enabled=lp_config_get_int(lc->config,"sound","noisegate",0);
995                 audio_stream_enable_noise_gate(audiostream,enabled);
996         }
997
998         audio_stream_set_features(audiostream,linphone_core_get_audio_features(lc));
999
1000         if (lc->rtptf){
1001                 RtpTransport *artp=lc->rtptf->audio_rtp_func(lc->rtptf->audio_rtp_func_data, call->audio_port);
1002                 RtpTransport *artcp=lc->rtptf->audio_rtcp_func(lc->rtptf->audio_rtcp_func_data, call->audio_port+1);
1003                 rtp_session_set_transports(audiostream->session,artp,artcp);
1004         }
1005         if ((linphone_core_get_firewall_policy(lc) == LinphonePolicyUseIce) && (call->ice_session != NULL)){
1006                 rtp_session_set_pktinfo(audiostream->session, TRUE);
1007                 rtp_session_set_symmetric_rtp(audiostream->session, FALSE);
1008                 if (ice_session_check_list(call->ice_session, 0) == NULL) {
1009                         ice_session_add_check_list(call->ice_session, ice_check_list_new());
1010                 }
1011                 audiostream->ice_check_list = ice_session_check_list(call->ice_session, 0);
1012                 ice_check_list_set_rtp_session(audiostream->ice_check_list, audiostream->session);
1013         }
1014
1015         call->audiostream_app_evq = ortp_ev_queue_new();
1016         rtp_session_register_event_queue(audiostream->session,call->audiostream_app_evq);
1017 }
1018
1019 void linphone_call_init_video_stream(LinphoneCall *call){
1020 #ifdef VIDEO_ENABLED
1021         LinphoneCore *lc=call->core;
1022
1023         if ((lc->video_conf.display || lc->video_conf.capture) && call->params.has_video){
1024                 int video_recv_buf_size=lp_config_get_int(lc->config,"video","recv_buf_size",0);
1025                 int dscp=linphone_core_get_video_dscp(lc);
1026                 
1027                 call->videostream=video_stream_new(call->video_port,call->video_port+1,linphone_core_ipv6_enabled(lc));
1028                 if (dscp!=-1)
1029                         video_stream_set_dscp(call->videostream,dscp);
1030                 video_stream_enable_display_filter_auto_rotate(call->videostream, lp_config_get_int(lc->config,"video","display_filter_auto_rotate",0));
1031                 if (video_recv_buf_size>0) rtp_session_set_recv_buf_size(call->videostream->session,video_recv_buf_size);
1032
1033                 if( lc->video_conf.displaytype != NULL)
1034                         video_stream_set_display_filter_name(call->videostream,lc->video_conf.displaytype);
1035                 video_stream_set_event_callback(call->videostream,video_stream_event_cb, call);
1036                 if (lc->rtptf){
1037                         RtpTransport *vrtp=lc->rtptf->video_rtp_func(lc->rtptf->video_rtp_func_data, call->video_port);
1038                         RtpTransport *vrtcp=lc->rtptf->video_rtcp_func(lc->rtptf->video_rtcp_func_data, call->video_port+1);
1039                         rtp_session_set_transports(call->videostream->session,vrtp,vrtcp);
1040                 }
1041                 if ((linphone_core_get_firewall_policy(lc) == LinphonePolicyUseIce) && (call->ice_session != NULL) && (ice_session_check_list(call->ice_session, 1))){
1042                         rtp_session_set_pktinfo(call->videostream->session, TRUE);
1043                         rtp_session_set_symmetric_rtp(call->videostream->session, FALSE);
1044                         if (ice_session_check_list(call->ice_session, 1) == NULL) {
1045                                 ice_session_add_check_list(call->ice_session, ice_check_list_new());
1046                         }
1047                         call->videostream->ice_check_list = ice_session_check_list(call->ice_session, 1);
1048                         ice_check_list_set_rtp_session(call->videostream->ice_check_list, call->videostream->session);
1049                 }
1050                 call->videostream_app_evq = ortp_ev_queue_new();
1051                 rtp_session_register_event_queue(call->videostream->session,call->videostream_app_evq);
1052 #ifdef TEST_EXT_RENDERER
1053                 video_stream_set_render_callback(call->videostream,rendercb,NULL);
1054 #endif
1055         }
1056 #else
1057         call->videostream=NULL;
1058 #endif
1059 }
1060
1061 void linphone_call_init_media_streams(LinphoneCall *call){
1062         linphone_call_init_audio_stream(call);
1063         linphone_call_init_video_stream(call);
1064 }
1065
1066
1067 static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'};
1068
1069 static void linphone_core_dtmf_received(RtpSession* s, int dtmf, void* user_data){
1070         LinphoneCore* lc = (LinphoneCore*)user_data;
1071         if (dtmf<0 || dtmf>15){
1072                 ms_warning("Bad dtmf value %i",dtmf);
1073                 return;
1074         }
1075         if (lc->vtable.dtmf_received != NULL)
1076                 lc->vtable.dtmf_received(lc, linphone_core_get_current_call(lc), dtmf_tab[dtmf]);
1077 }
1078
1079 static void parametrize_equalizer(LinphoneCore *lc, AudioStream *st){
1080         if (st->equalizer){
1081                 MSFilter *f=st->equalizer;
1082                 int enabled=lp_config_get_int(lc->config,"sound","eq_active",0);
1083                 const char *gains=lp_config_get_string(lc->config,"sound","eq_gains",NULL);
1084                 ms_filter_call_method(f,MS_EQUALIZER_SET_ACTIVE,&enabled);
1085                 if (enabled){
1086                         if (gains){
1087                                 do{
1088                                         int bytes;
1089                                         MSEqualizerGain g;
1090                                         if (sscanf(gains,"%f:%f:%f %n",&g.frequency,&g.gain,&g.width,&bytes)==3){
1091                                                 ms_message("Read equalizer gains: %f(~%f) --> %f",g.frequency,g.width,g.gain);
1092                                                 ms_filter_call_method(f,MS_EQUALIZER_SET_GAIN,&g);
1093                                                 gains+=bytes;
1094                                         }else break;
1095                                 }while(1);
1096                         }
1097                 }
1098         }
1099 }
1100
1101 void _post_configure_audio_stream(AudioStream *st, LinphoneCore *lc, bool_t muted){
1102         float mic_gain=lp_config_get_float(lc->config,"sound","mic_gain",1);
1103         float thres = 0;
1104         float recv_gain;
1105         float ng_thres=lp_config_get_float(lc->config,"sound","ng_thres",0.05);
1106         float ng_floorgain=lp_config_get_float(lc->config,"sound","ng_floorgain",0);
1107         int dc_removal=lp_config_get_int(lc->config,"sound","dc_removal",0);
1108
1109         if (!muted)
1110                 audio_stream_set_mic_gain(st,mic_gain);
1111         else
1112                 audio_stream_set_mic_gain(st,0);
1113
1114         recv_gain = lc->sound_conf.soft_play_lev;
1115         if (recv_gain != 0) {
1116                 linphone_core_set_playback_gain_db (lc,recv_gain);
1117         }
1118         
1119         if (st->volsend){
1120                 ms_filter_call_method(st->volsend,MS_VOLUME_REMOVE_DC,&dc_removal);
1121                 float speed=lp_config_get_float(lc->config,"sound","el_speed",-1);
1122                 thres=lp_config_get_float(lc->config,"sound","el_thres",-1);
1123                 float force=lp_config_get_float(lc->config,"sound","el_force",-1);
1124                 int sustain=lp_config_get_int(lc->config,"sound","el_sustain",-1);
1125                 float transmit_thres=lp_config_get_float(lc->config,"sound","el_transmit_thres",-1);
1126                 MSFilter *f=NULL;
1127                 f=st->volsend;
1128                 if (speed==-1) speed=0.03;
1129                 if (force==-1) force=25;
1130                 ms_filter_call_method(f,MS_VOLUME_SET_EA_SPEED,&speed);
1131                 ms_filter_call_method(f,MS_VOLUME_SET_EA_FORCE,&force);
1132                 if (thres!=-1)
1133                         ms_filter_call_method(f,MS_VOLUME_SET_EA_THRESHOLD,&thres);
1134                 if (sustain!=-1)
1135                         ms_filter_call_method(f,MS_VOLUME_SET_EA_SUSTAIN,&sustain);
1136                 if (transmit_thres!=-1)
1137                                 ms_filter_call_method(f,MS_VOLUME_SET_EA_TRANSMIT_THRESHOLD,&transmit_thres);
1138
1139                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_thres);
1140                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&ng_floorgain);
1141         }
1142         if (st->volrecv){
1143                 /* parameters for a limited noise-gate effect, using echo limiter threshold */
1144                 float floorgain = 1/mic_gain;
1145                 int spk_agc=lp_config_get_int(lc->config,"sound","speaker_agc_enabled",0);
1146                 ms_filter_call_method(st->volrecv, MS_VOLUME_ENABLE_AGC, &spk_agc);
1147                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_thres);
1148                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&floorgain);
1149         }
1150         parametrize_equalizer(lc,st);
1151 }
1152
1153 static void post_configure_audio_streams(LinphoneCall*call){
1154         AudioStream *st=call->audiostream;
1155         LinphoneCore *lc=call->core;
1156         _post_configure_audio_stream(st,lc,call->audio_muted);
1157         if (lc->vtable.dtmf_received!=NULL){
1158                 /* replace by our default action*/
1159                 audio_stream_play_received_dtmfs(call->audiostream,FALSE);
1160                 rtp_session_signal_connect(call->audiostream->session,"telephone-event",(RtpCallback)linphone_core_dtmf_received,(unsigned long)lc);
1161         }
1162 }
1163
1164 static RtpProfile *make_profile(LinphoneCall *call, const SalMediaDescription *md, const SalStreamDescription *desc, int *used_pt){
1165         int bw;
1166         const MSList *elem;
1167         RtpProfile *prof=rtp_profile_new("Call profile");
1168         bool_t first=TRUE;
1169         int remote_bw=0;
1170         LinphoneCore *lc=call->core;
1171         int up_ptime=0;
1172         const LinphoneCallParams *params=&call->params;
1173         *used_pt=-1;
1174
1175         for(elem=desc->payloads;elem!=NULL;elem=elem->next){
1176                 PayloadType *pt=(PayloadType*)elem->data;
1177                 int number;
1178
1179                 if ((pt->flags & PAYLOAD_TYPE_FLAG_CAN_SEND) && first) {
1180                         if (desc->type==SalAudio){
1181                                 linphone_core_update_allocated_audio_bandwidth_in_call(call,pt);
1182                                 if (params->up_ptime)
1183                                         up_ptime=params->up_ptime;
1184                                 else up_ptime=linphone_core_get_upload_ptime(lc);
1185                         }
1186                         *used_pt=payload_type_get_number(pt);
1187                         first=FALSE;
1188                 }
1189                 if (desc->bandwidth>0) remote_bw=desc->bandwidth;
1190                 else if (md->bandwidth>0) {
1191                         /*case where b=AS is given globally, not per stream*/
1192                         remote_bw=md->bandwidth;
1193                         if (desc->type==SalVideo){
1194                                 remote_bw=get_video_bandwidth(remote_bw,call->audio_bw);
1195                         }
1196                 }
1197
1198                 if (desc->type==SalAudio){
1199                         int audio_bw=call->audio_bw;
1200                         if (params->up_bw){
1201                                 if (params->up_bw< audio_bw)
1202                                         audio_bw=params->up_bw;
1203                         }
1204                         bw=get_min_bandwidth(audio_bw,remote_bw);
1205                 }else bw=get_min_bandwidth(get_video_bandwidth(linphone_core_get_upload_bandwidth (lc),call->audio_bw),remote_bw);
1206                 if (bw>0) pt->normal_bitrate=bw*1000;
1207                 else if (desc->type==SalAudio){
1208                         pt->normal_bitrate=-1;
1209                 }
1210                 if (desc->ptime>0){
1211                         up_ptime=desc->ptime;
1212                 }
1213                 if (up_ptime>0){
1214                         char tmp[40];
1215                         snprintf(tmp,sizeof(tmp),"ptime=%i",up_ptime);
1216                         payload_type_append_send_fmtp(pt,tmp);
1217                 }
1218                 number=payload_type_get_number(pt);
1219                 if (rtp_profile_get_payload(prof,number)!=NULL){
1220                         ms_warning("A payload type with number %i already exists in profile !",number);
1221                 }else
1222                         rtp_profile_set_payload(prof,number,pt);
1223         }
1224         return prof;
1225 }
1226
1227
1228 static void setup_ring_player(LinphoneCore *lc, LinphoneCall *call){
1229         int pause_time=3000;
1230         audio_stream_play(call->audiostream,lc->sound_conf.ringback_tone);
1231         ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
1232 }
1233
1234 #define LINPHONE_RTCP_SDES_TOOL "Linphone-" LINPHONE_VERSION
1235
1236 static bool_t linphone_call_sound_resources_available(LinphoneCall *call){
1237         LinphoneCore *lc=call->core;
1238         LinphoneCall *current=linphone_core_get_current_call(lc);
1239         return !linphone_core_is_in_conference(lc) && 
1240                 (current==NULL || current==call);
1241 }
1242 static int find_crypto_index_from_tag(const SalSrtpCryptoAlgo crypto[],unsigned char tag) {
1243     int i;
1244     for(i=0; i<SAL_CRYPTO_ALGO_MAX; i++) {
1245         if (crypto[i].tag == tag) {
1246             return i;
1247         }
1248     }
1249     return -1;
1250 }
1251 static void linphone_call_start_audio_stream(LinphoneCall *call, const char *cname, bool_t muted, bool_t send_ringbacktone, bool_t use_arc){
1252         LinphoneCore *lc=call->core;
1253         int used_pt=-1;
1254         /* look for savp stream first */
1255         const SalStreamDescription *stream=sal_media_description_find_stream(call->resultdesc,
1256                                                 SalProtoRtpSavp,SalAudio);
1257         /* no savp audio stream, use avp */
1258         if (!stream)
1259                 stream=sal_media_description_find_stream(call->resultdesc,
1260                                                 SalProtoRtpAvp,SalAudio);
1261
1262         if (stream && stream->dir!=SalStreamInactive && stream->rtp_port!=0){
1263                 MSSndCard *playcard=lc->sound_conf.lsd_card ?
1264                         lc->sound_conf.lsd_card : lc->sound_conf.play_sndcard;
1265                 MSSndCard *captcard=lc->sound_conf.capt_sndcard;
1266                 const char *playfile=lc->play_file;
1267                 const char *recfile=lc->rec_file;
1268                 call->audio_profile=make_profile(call,call->resultdesc,stream,&used_pt);
1269                 bool_t use_ec;
1270
1271                 if (used_pt!=-1){
1272                         call->current_params.audio_codec = rtp_profile_get_payload(call->audio_profile, used_pt);
1273                         if (playcard==NULL) {
1274                                 ms_warning("No card defined for playback !");
1275                         }
1276                         if (captcard==NULL) {
1277                                 ms_warning("No card defined for capture !");
1278                         }
1279                         /*Replace soundcard filters by inactive file players or recorders
1280                          when placed in recvonly or sendonly mode*/
1281                         if (stream->rtp_port==0 || stream->dir==SalStreamRecvOnly){
1282                                 captcard=NULL;
1283                                 playfile=NULL;
1284                         }else if (stream->dir==SalStreamSendOnly){
1285                                 playcard=NULL;
1286                                 captcard=NULL;
1287                                 recfile=NULL;
1288                                 /*And we will eventually play "playfile" if set by the user*/
1289                                 /*playfile=NULL;*/
1290                         }
1291                         if (send_ringbacktone){
1292                                 captcard=NULL;
1293                                 playfile=NULL;/* it is setup later*/
1294                         }
1295                         /*if playfile are supplied don't use soundcards*/
1296                         if (lc->use_files) {
1297                                 captcard=NULL;
1298                                 playcard=NULL;
1299                         }
1300                         if (call->params.in_conference){
1301                                 /* first create the graph without soundcard resources*/
1302                                 captcard=playcard=NULL;
1303                         }
1304                         if (!linphone_call_sound_resources_available(call)){
1305                                 ms_message("Sound resources are used by another call, not using soundcard.");
1306                                 captcard=playcard=NULL;
1307                         }
1308                         use_ec=captcard==NULL ? FALSE : linphone_core_echo_cancellation_enabled(lc);
1309                         if (playcard &&  stream->max_rate>0) ms_snd_card_set_preferred_sample_rate(playcard, stream->max_rate);
1310                         if (captcard &&  stream->max_rate>0) ms_snd_card_set_preferred_sample_rate(captcard, stream->max_rate);
1311                         audio_stream_enable_adaptive_bitrate_control(call->audiostream,use_arc);
1312                         audio_stream_enable_adaptive_jittcomp(call->audiostream, linphone_core_audio_adaptive_jittcomp_enabled(lc));
1313                         audio_stream_start_full(
1314                                 call->audiostream,
1315                                 call->audio_profile,
1316                                 stream->rtp_addr[0]!='\0' ? stream->rtp_addr : call->resultdesc->addr,
1317                                 stream->rtp_port,
1318                                 stream->rtcp_addr[0]!='\0' ? stream->rtcp_addr : call->resultdesc->addr,
1319                                 linphone_core_rtcp_enabled(lc) ? (stream->rtcp_port) : 0,
1320                                 used_pt,
1321                                 linphone_core_get_audio_jittcomp(lc),
1322                                 playfile,
1323                                 recfile,
1324                                 playcard,
1325                                 captcard,
1326                                 use_ec
1327                                 );
1328                         post_configure_audio_streams(call);
1329                         if (muted && !send_ringbacktone){
1330                                 audio_stream_set_mic_gain(call->audiostream,0);
1331                         }
1332                         if (stream->dir==SalStreamSendOnly && playfile!=NULL){
1333                                 int pause_time=500;
1334                                 ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
1335                         }
1336                         if (send_ringbacktone){
1337                                 setup_ring_player(lc,call);
1338                         }
1339                         audio_stream_set_rtcp_information(call->audiostream, cname, LINPHONE_RTCP_SDES_TOOL);
1340                         
1341             /* valid local tags are > 0 */
1342                         if (stream->proto == SalProtoRtpSavp) {
1343                 const SalStreamDescription *local_st_desc=sal_media_description_find_stream(call->localdesc,
1344                                                                                             SalProtoRtpSavp,SalAudio);
1345                 int crypto_idx = find_crypto_index_from_tag(local_st_desc->crypto, stream->crypto_local_tag);
1346                 
1347                 if (crypto_idx >= 0) {
1348                     audio_stream_enable_strp(
1349                                              call->audiostream, 
1350                                              stream->crypto[0].algo,
1351                                              local_st_desc->crypto[crypto_idx].master_key,
1352                                              stream->crypto[0].master_key);
1353                     call->audiostream_encrypted=TRUE;
1354                 } else {
1355                     ms_warning("Failed to find local crypto algo with tag: %d", stream->crypto_local_tag);
1356                     call->audiostream_encrypted=FALSE;
1357                 }
1358                         }else call->audiostream_encrypted=FALSE;
1359                         if (call->params.in_conference){
1360                                 /*transform the graph to connect it to the conference filter */
1361                                 bool_t mute=stream->dir==SalStreamRecvOnly;
1362                                 linphone_call_add_to_conf(call, mute);
1363                         }
1364                         call->current_params.in_conference=call->params.in_conference;
1365                 }else ms_warning("No audio stream accepted ?");
1366         }
1367 }
1368
1369 static void linphone_call_start_video_stream(LinphoneCall *call, const char *cname,bool_t all_inputs_muted){
1370 #ifdef VIDEO_ENABLED
1371         LinphoneCore *lc=call->core;
1372         int used_pt=-1;
1373         /* look for savp stream first */
1374         const SalStreamDescription *vstream=sal_media_description_find_stream(call->resultdesc,
1375                                                 SalProtoRtpSavp,SalVideo);
1376         /* no savp audio stream, use avp */
1377         if (!vstream)
1378                 vstream=sal_media_description_find_stream(call->resultdesc,
1379                                                 SalProtoRtpAvp,SalVideo);
1380                                                 
1381         /* shutdown preview */
1382         if (lc->previewstream!=NULL) {
1383                 video_preview_stop(lc->previewstream);
1384                 lc->previewstream=NULL;
1385         }
1386         
1387         if (vstream!=NULL && vstream->dir!=SalStreamInactive && vstream->rtp_port!=0) {
1388                 const char *rtp_addr=vstream->rtp_addr[0]!='\0' ? vstream->rtp_addr : call->resultdesc->addr;
1389                 const char *rtcp_addr=vstream->rtcp_addr[0]!='\0' ? vstream->rtcp_addr : call->resultdesc->addr;
1390                 call->video_profile=make_profile(call,call->resultdesc,vstream,&used_pt);
1391                 if (used_pt!=-1){
1392                         call->current_params.video_codec = rtp_profile_get_payload(call->video_profile, used_pt);
1393                         VideoStreamDir dir=VideoStreamSendRecv;
1394                         MSWebCam *cam=lc->video_conf.device;
1395                         bool_t is_inactive=FALSE;
1396
1397                         call->current_params.has_video=TRUE;
1398
1399                         video_stream_enable_adaptive_bitrate_control(call->videostream,
1400                                                                   linphone_core_adaptive_rate_control_enabled(lc));
1401                         video_stream_enable_adaptive_jittcomp(call->videostream, linphone_core_video_adaptive_jittcomp_enabled(lc));
1402                         video_stream_set_sent_video_size(call->videostream,linphone_core_get_preferred_video_size(lc));
1403                         video_stream_enable_self_view(call->videostream,lc->video_conf.selfview);
1404                         if (lc->video_window_id!=0)
1405                                 video_stream_set_native_window_id(call->videostream,lc->video_window_id);
1406                         if (lc->preview_window_id!=0)
1407                                 video_stream_set_native_preview_window_id (call->videostream,lc->preview_window_id);
1408                         video_stream_use_preview_video_window (call->videostream,lc->use_preview_window);
1409                         
1410                         if (vstream->dir==SalStreamSendOnly && lc->video_conf.capture ){
1411                                 cam=get_nowebcam_device();
1412                                 dir=VideoStreamSendOnly;
1413                         }else if (vstream->dir==SalStreamRecvOnly && lc->video_conf.display ){
1414                                 dir=VideoStreamRecvOnly;
1415                         }else if (vstream->dir==SalStreamSendRecv){
1416                                 if (lc->video_conf.display && lc->video_conf.capture)
1417                                         dir=VideoStreamSendRecv;
1418                                 else if (lc->video_conf.display)
1419                                         dir=VideoStreamRecvOnly;
1420                                 else
1421                                         dir=VideoStreamSendOnly;
1422                         }else{
1423                                 ms_warning("video stream is inactive.");
1424                                 /*either inactive or incompatible with local capabilities*/
1425                                 is_inactive=TRUE;
1426                         }
1427                         if (call->camera_active==FALSE || all_inputs_muted){
1428                                 cam=get_nowebcam_device();
1429                         }
1430                         if (!is_inactive){
1431                 call->log->video_enabled = TRUE;
1432                                 video_stream_set_direction (call->videostream, dir);
1433                                 ms_message("%s lc rotation:%d\n", __FUNCTION__, lc->device_rotation);
1434                                 video_stream_set_device_rotation(call->videostream, lc->device_rotation);
1435                                 video_stream_start(call->videostream,
1436                                         call->video_profile, rtp_addr, vstream->rtp_port,
1437                                         rtcp_addr, linphone_core_rtcp_enabled(lc) ? (vstream->rtcp_port) : 0,
1438                                         used_pt, linphone_core_get_video_jittcomp(lc), cam);
1439                                 video_stream_set_rtcp_information(call->videostream, cname,LINPHONE_RTCP_SDES_TOOL);
1440                         }
1441                         
1442                         if (vstream->proto == SalProtoRtpSavp) {
1443                                 const SalStreamDescription *local_st_desc=sal_media_description_find_stream(call->localdesc,
1444                                                 SalProtoRtpSavp,SalVideo);
1445                                                 
1446                                 video_stream_enable_strp(
1447                                         call->videostream, 
1448                                         vstream->crypto[0].algo,
1449                                         local_st_desc->crypto[0].master_key, 
1450                                         vstream->crypto[0].master_key
1451                                         );
1452                                 call->videostream_encrypted=TRUE;
1453                         }else{
1454                                 call->videostream_encrypted=FALSE;
1455                         }
1456                 }else ms_warning("No video stream accepted.");
1457         }else{
1458                 ms_warning("No valid video stream defined.");
1459         }
1460 #endif
1461 }
1462
1463 void linphone_call_start_media_streams(LinphoneCall *call, bool_t all_inputs_muted, bool_t send_ringbacktone){
1464         LinphoneCore *lc=call->core;
1465
1466         call->current_params.audio_codec = NULL;
1467         call->current_params.video_codec = NULL;
1468
1469         LinphoneAddress *me=linphone_core_get_primary_contact_parsed(lc);
1470         char *cname;
1471         bool_t use_arc=linphone_core_adaptive_rate_control_enabled(lc);
1472 #ifdef VIDEO_ENABLED
1473         const SalStreamDescription *vstream=sal_media_description_find_stream(call->resultdesc,
1474                                                         SalProtoRtpAvp,SalVideo);
1475 #endif
1476
1477         if ((call->audiostream == NULL) && (call->videostream == NULL)) {
1478                 ms_fatal("start_media_stream() called without prior init !");
1479                 return;
1480         }
1481         cname=linphone_address_as_string_uri_only(me);
1482
1483 #if defined(VIDEO_ENABLED)
1484         if (vstream!=NULL && vstream->dir!=SalStreamInactive && vstream->payloads!=NULL){
1485                 /*when video is used, do not make adaptive rate control on audio, it is stupid.*/
1486                 use_arc=FALSE;
1487         }
1488 #endif
1489         if (call->audiostream!=NULL) {
1490                 linphone_call_start_audio_stream(call,cname,all_inputs_muted,send_ringbacktone,use_arc);
1491         }
1492         call->current_params.has_video=FALSE;
1493         if (call->videostream!=NULL) {
1494                 linphone_call_start_video_stream(call,cname,all_inputs_muted);
1495         }
1496
1497         call->all_muted=all_inputs_muted;
1498         call->playing_ringbacktone=send_ringbacktone;
1499         call->up_bw=linphone_core_get_upload_bandwidth(lc);
1500
1501         if (call->params.media_encryption==LinphoneMediaEncryptionZRTP) {
1502                 OrtpZrtpParams params;
1503                 /*will be set later when zrtp is activated*/
1504                 call->current_params.media_encryption=LinphoneMediaEncryptionNone;
1505                 
1506                 params.zid_file=lc->zrtp_secrets_cache;
1507                 audio_stream_enable_zrtp(call->audiostream,&params);
1508         }else if (call->params.media_encryption==LinphoneMediaEncryptionSRTP){
1509                 call->current_params.media_encryption=linphone_call_are_all_streams_encrypted(call) ?
1510                         LinphoneMediaEncryptionSRTP : LinphoneMediaEncryptionNone;
1511         }
1512
1513         /*also reflect the change if the "wished" params, in order to avoid to propose SAVP or video again
1514          * further in the call, for example during pause,resume, conferencing reINVITEs*/
1515         linphone_call_fix_call_parameters(call);
1516         if ((call->ice_session != NULL) && (ice_session_state(call->ice_session) != IS_Completed)) {
1517                 ice_session_start_connectivity_checks(call->ice_session);
1518         }
1519
1520         goto end;
1521         end:
1522                 ms_free(cname);
1523                 linphone_address_destroy(me);
1524 }
1525
1526 void linphone_call_start_media_streams_for_ice_gathering(LinphoneCall *call){
1527         audio_stream_prepare_sound(call->audiostream, NULL, NULL);
1528 #ifdef VIDEO_ENABLED
1529         if (call->videostream) {
1530                 video_stream_prepare_video(call->videostream);
1531         }
1532 #endif
1533 }
1534
1535 void linphone_call_delete_ice_session(LinphoneCall *call){
1536         if (call->ice_session != NULL) {
1537                 ice_session_destroy(call->ice_session);
1538                 call->ice_session = NULL;
1539                 if (call->audiostream != NULL) call->audiostream->ice_check_list = NULL;
1540                 if (call->videostream != NULL) call->videostream->ice_check_list = NULL;
1541                 call->stats[LINPHONE_CALL_STATS_AUDIO].ice_state = LinphoneIceStateNotActivated;
1542                 call->stats[LINPHONE_CALL_STATS_VIDEO].ice_state = LinphoneIceStateNotActivated;
1543         }
1544 }
1545
1546 static void linphone_call_log_fill_stats(LinphoneCallLog *log, AudioStream *st){
1547         audio_stream_get_local_rtp_stats (st,&log->local_stats);
1548         log->quality=audio_stream_get_average_quality_rating(st);
1549 }
1550
1551 void linphone_call_stop_media_streams(LinphoneCall *call){
1552         if (call->audiostream!=NULL) {
1553                 call->audiostream->ice_check_list = NULL;
1554                 rtp_session_unregister_event_queue(call->audiostream->session,call->audiostream_app_evq);
1555                 ortp_ev_queue_flush(call->audiostream_app_evq);
1556                 ortp_ev_queue_destroy(call->audiostream_app_evq);
1557                 call->audiostream_app_evq=NULL;
1558
1559                 if (call->audiostream->ec){
1560                         const char *state_str=NULL;
1561                         ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_GET_STATE_STRING,&state_str);
1562                         if (state_str){
1563                                 ms_message("Writing echo canceler state, %i bytes",(int)strlen(state_str));
1564                                 lp_config_set_string(call->core->config,"sound","ec_state",state_str);
1565                         }
1566                 }
1567                 linphone_call_log_fill_stats (call->log,call->audiostream);
1568                 if (call->endpoint){
1569                         linphone_call_remove_from_conf(call);
1570                 }
1571                 audio_stream_stop(call->audiostream);
1572                 call->audiostream=NULL;
1573         }
1574
1575
1576 #ifdef VIDEO_ENABLED
1577         if (call->videostream!=NULL){
1578                 call->videostream->ice_check_list = NULL;
1579                 rtp_session_unregister_event_queue(call->videostream->session,call->videostream_app_evq);
1580                 ortp_ev_queue_flush(call->videostream_app_evq);
1581                 ortp_ev_queue_destroy(call->videostream_app_evq);
1582                 call->videostream_app_evq=NULL;
1583                 video_stream_stop(call->videostream);
1584                 call->videostream=NULL;
1585         }
1586 #endif
1587         ms_event_queue_skip(call->core->msevq);
1588         
1589         if (call->audio_profile){
1590                 rtp_profile_clear_all(call->audio_profile);
1591                 rtp_profile_destroy(call->audio_profile);
1592                 call->audio_profile=NULL;
1593         }
1594         if (call->video_profile){
1595                 rtp_profile_clear_all(call->video_profile);
1596                 rtp_profile_destroy(call->video_profile);
1597                 call->video_profile=NULL;
1598         }
1599 }
1600
1601
1602
1603 void linphone_call_enable_echo_cancellation(LinphoneCall *call, bool_t enable) {
1604         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
1605                 bool_t bypass_mode = !enable;
1606                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_SET_BYPASS_MODE,&bypass_mode);
1607         }
1608 }
1609 bool_t linphone_call_echo_cancellation_enabled(LinphoneCall *call) {
1610         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
1611                 bool_t val;
1612                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_GET_BYPASS_MODE,&val);
1613                 return !val;
1614         } else {
1615                 return linphone_core_echo_cancellation_enabled(call->core);
1616         }
1617 }
1618
1619 void linphone_call_enable_echo_limiter(LinphoneCall *call, bool_t val){
1620         if (call!=NULL && call->audiostream!=NULL ) {
1621                 if (val) {
1622                 const char *type=lp_config_get_string(call->core->config,"sound","el_type","mic");
1623                 if (strcasecmp(type,"mic")==0)
1624                         audio_stream_enable_echo_limiter(call->audiostream,ELControlMic);
1625                 else if (strcasecmp(type,"full")==0)
1626                         audio_stream_enable_echo_limiter(call->audiostream,ELControlFull);
1627                 } else {
1628                         audio_stream_enable_echo_limiter(call->audiostream,ELInactive);
1629                 }
1630         }
1631 }
1632
1633 bool_t linphone_call_echo_limiter_enabled(const LinphoneCall *call){
1634         if (call!=NULL && call->audiostream!=NULL ){
1635                 return call->audiostream->el_type !=ELInactive ;
1636         } else {
1637                 return linphone_core_echo_limiter_enabled(call->core);
1638         }
1639 }
1640
1641 /**
1642  * @addtogroup call_misc
1643  * @{
1644 **/
1645
1646 /**
1647  * Returns the measured sound volume played locally (received from remote).
1648  * It is expressed in dbm0.
1649 **/
1650 float linphone_call_get_play_volume(LinphoneCall *call){
1651         AudioStream *st=call->audiostream;
1652         if (st && st->volrecv){
1653                 float vol=0;
1654                 ms_filter_call_method(st->volrecv,MS_VOLUME_GET,&vol);
1655                 return vol;
1656
1657         }
1658         return LINPHONE_VOLUME_DB_LOWEST;
1659 }
1660
1661 /**
1662  * Returns the measured sound volume recorded locally (sent to remote).
1663  * It is expressed in dbm0.
1664 **/
1665 float linphone_call_get_record_volume(LinphoneCall *call){
1666         AudioStream *st=call->audiostream;
1667         if (st && st->volsend && !call->audio_muted && call->state==LinphoneCallStreamsRunning){
1668                 float vol=0;
1669                 ms_filter_call_method(st->volsend,MS_VOLUME_GET,&vol);
1670                 return vol;
1671
1672         }
1673         return LINPHONE_VOLUME_DB_LOWEST;
1674 }
1675
1676 /**
1677  * Obtain real-time quality rating of the call
1678  *
1679  * Based on local RTP statistics and RTCP feedback, a quality rating is computed and updated
1680  * during all the duration of the call. This function returns its value at the time of the function call.
1681  * It is expected that the rating is updated at least every 5 seconds or so.
1682  * The rating is a floating point number comprised between 0 and 5.
1683  *
1684  * 4-5 = good quality <br>
1685  * 3-4 = average quality <br>
1686  * 2-3 = poor quality <br>
1687  * 1-2 = very poor quality <br>
1688  * 0-1 = can't be worse, mostly unusable <br>
1689  *
1690  * @returns The function returns -1 if no quality measurement is available, for example if no
1691  * active audio stream exist. Otherwise it returns the quality rating.
1692 **/
1693 float linphone_call_get_current_quality(LinphoneCall *call){
1694         if (call->audiostream){
1695                 return audio_stream_get_quality_rating(call->audiostream);
1696         }
1697         return -1;
1698 }
1699
1700 /**
1701  * Returns call quality averaged over all the duration of the call.
1702  *
1703  * See linphone_call_get_current_quality() for more details about quality measurement.
1704 **/
1705 float linphone_call_get_average_quality(LinphoneCall *call){
1706         if (call->audiostream){
1707                 return audio_stream_get_average_quality_rating(call->audiostream);
1708         }
1709         return -1;
1710 }
1711
1712 /**
1713  * Access last known statistics for audio stream, for a given call.
1714 **/
1715 const LinphoneCallStats *linphone_call_get_audio_stats(const LinphoneCall *call) {
1716         return &call->stats[LINPHONE_CALL_STATS_AUDIO];
1717 }
1718
1719 /**
1720  * Access last known statistics for video stream, for a given call.
1721 **/
1722 const LinphoneCallStats *linphone_call_get_video_stats(const LinphoneCall *call) {
1723         return &call->stats[LINPHONE_CALL_STATS_VIDEO];
1724 }
1725
1726
1727 /**
1728  * @}
1729 **/
1730
1731 static void report_bandwidth(LinphoneCall *call, RtpSession *as, RtpSession *vs){
1732         call->stats[LINPHONE_CALL_STATS_AUDIO].download_bandwidth=(as!=NULL) ? (rtp_session_compute_recv_bandwidth(as)*1e-3) : 0;
1733         call->stats[LINPHONE_CALL_STATS_AUDIO].upload_bandwidth=(as!=NULL) ? (rtp_session_compute_send_bandwidth(as)*1e-3) : 0;
1734         call->stats[LINPHONE_CALL_STATS_VIDEO].download_bandwidth=(vs!=NULL) ? (rtp_session_compute_recv_bandwidth(vs)*1e-3) : 0;
1735         call->stats[LINPHONE_CALL_STATS_VIDEO].upload_bandwidth=(vs!=NULL) ? (rtp_session_compute_send_bandwidth(vs)*1e-3) : 0;
1736         ms_message("bandwidth usage: audio=[d=%.1f,u=%.1f] video=[d=%.1f,u=%.1f] kbit/sec",
1737                 call->stats[LINPHONE_CALL_STATS_AUDIO].download_bandwidth,
1738                 call->stats[LINPHONE_CALL_STATS_AUDIO].upload_bandwidth ,
1739                 call->stats[LINPHONE_CALL_STATS_VIDEO].download_bandwidth,
1740                 call->stats[LINPHONE_CALL_STATS_VIDEO].upload_bandwidth
1741         );
1742 }
1743
1744 static void linphone_core_disconnected(LinphoneCore *lc, LinphoneCall *call){
1745         char temp[256];
1746         char *from=NULL;
1747         if(call)
1748                 from = linphone_call_get_remote_address_as_string(call);
1749         if (from)
1750         {
1751                 snprintf(temp,sizeof(temp),"Remote end %s seems to have disconnected, the call is going to be closed.",from);
1752                 free(from);
1753         }
1754         else
1755         {
1756                 snprintf(temp,sizeof(temp),"Remote end seems to have disconnected, the call is going to be closed.");
1757         }
1758         if (lc->vtable.display_warning!=NULL)
1759                 lc->vtable.display_warning(lc,temp);
1760         linphone_core_terminate_call(lc,call);
1761 }
1762
1763 static void handle_ice_events(LinphoneCall *call, OrtpEvent *ev){
1764         OrtpEventType evt=ortp_event_get_type(ev);
1765         OrtpEventData *evd=ortp_event_get_data(ev);
1766         int ping_time;
1767
1768         if (evt == ORTP_EVENT_ICE_SESSION_PROCESSING_FINISHED) {
1769                 switch (ice_session_state(call->ice_session)) {
1770                         case IS_Completed:
1771                                 ice_session_select_candidates(call->ice_session);
1772                                 if (ice_session_role(call->ice_session) == IR_Controlling) {
1773                                         linphone_core_update_call(call->core, call, &call->current_params);
1774                                 }
1775                                 break;
1776                         case IS_Failed:
1777                                 if (ice_session_has_completed_check_list(call->ice_session) == TRUE) {
1778                                         ice_session_select_candidates(call->ice_session);
1779                                         if (ice_session_role(call->ice_session) == IR_Controlling) {
1780                                                 /* At least one ICE session has succeeded, so perform a call update. */
1781                                                 linphone_core_update_call(call->core, call, &call->current_params);
1782                                         }
1783                                 }
1784                                 break;
1785                         default:
1786                                 break;
1787                 }
1788                 linphone_core_update_ice_state_in_call_stats(call);
1789         } else if (evt == ORTP_EVENT_ICE_GATHERING_FINISHED) {
1790
1791                 if (evd->info.ice_processing_successful==TRUE) {
1792                         ice_session_compute_candidates_foundations(call->ice_session);
1793                         ice_session_eliminate_redundant_candidates(call->ice_session);
1794                         ice_session_choose_default_candidates(call->ice_session);
1795                         ping_time = ice_session_gathering_duration(call->ice_session);
1796                         if (ping_time >=0) {
1797                                 ping_time /= ice_session_nb_check_lists(call->ice_session);
1798                                 call->ping_time=ping_time;
1799                         }
1800                 } else {
1801                         ms_warning("No STUN answer from [%s], disabling ICE",linphone_core_get_stun_server(call->core));
1802                         linphone_call_delete_ice_session(call);
1803                 }
1804                 switch (call->state) {
1805                         case LinphoneCallStreamsRunning:
1806                                 linphone_core_start_update_call(call->core, call);
1807                                 break;
1808                         case LinphoneCallUpdatedByRemote:
1809                                 linphone_core_start_accept_call_update(call->core, call);
1810                                 break;
1811                         case LinphoneCallOutgoingInit:
1812                                 linphone_call_stop_media_streams(call);
1813                                 linphone_core_proceed_with_invite_if_ready(call->core, call, NULL);
1814                                 break;
1815                         default:
1816                                 linphone_call_stop_media_streams(call);
1817                                 linphone_core_notify_incoming_call(call->core, call);
1818                                 break;
1819                 }
1820         } else if (evt == ORTP_EVENT_ICE_LOSING_PAIRS_COMPLETED) {
1821                 linphone_core_start_accept_call_update(call->core, call);
1822         } else if (evt == ORTP_EVENT_ICE_RESTART_NEEDED) {
1823                 ice_session_restart(call->ice_session);
1824                 ice_session_set_role(call->ice_session, IR_Controlling);
1825                 linphone_core_update_call(call->core, call, &call->current_params);
1826         }
1827 }
1828
1829 void linphone_call_background_tasks(LinphoneCall *call, bool_t one_second_elapsed){
1830         LinphoneCore* lc = call->core;
1831         int disconnect_timeout = linphone_core_get_nortp_timeout(call->core);
1832         bool_t disconnected=FALSE;
1833
1834         if (call->state==LinphoneCallStreamsRunning && one_second_elapsed){
1835                 RtpSession *as=NULL,*vs=NULL;
1836                 float audio_load=0, video_load=0;
1837                 if (call->audiostream!=NULL){
1838                         as=call->audiostream->session;
1839                         if (call->audiostream->ticker)
1840                                 audio_load=ms_ticker_get_average_load(call->audiostream->ticker);
1841                 }
1842                 if (call->videostream!=NULL){
1843                         if (call->videostream->ticker)
1844                                 video_load=ms_ticker_get_average_load(call->videostream->ticker);
1845                         vs=call->videostream->session;
1846                 }
1847                 report_bandwidth(call,as,vs);
1848                 ms_message("Thread processing load: audio=%f\tvideo=%f",audio_load,video_load);
1849         }
1850 #ifdef VIDEO_ENABLED
1851         if (call->videostream!=NULL) {
1852                 OrtpEvent *ev;
1853
1854                 /* Ensure there is no dangling ICE check list. */
1855                 if (call->ice_session == NULL) call->videostream->ice_check_list = NULL;
1856
1857                 // Beware that the application queue should not depend on treatments fron the
1858                 // mediastreamer queue.
1859                 video_stream_iterate(call->videostream);
1860
1861                 while (call->videostream_app_evq && (NULL != (ev=ortp_ev_queue_get(call->videostream_app_evq)))){
1862                         OrtpEventType evt=ortp_event_get_type(ev);
1863                         OrtpEventData *evd=ortp_event_get_data(ev);
1864                         if (evt == ORTP_EVENT_ZRTP_ENCRYPTION_CHANGED){
1865                                 linphone_call_videostream_encryption_changed(call, evd->info.zrtp_stream_encrypted);
1866                         } else if (evt == ORTP_EVENT_RTCP_PACKET_RECEIVED) {
1867                                 call->stats[LINPHONE_CALL_STATS_VIDEO].round_trip_delay = rtp_session_get_round_trip_propagation(call->videostream->session);
1868                                 if(call->stats[LINPHONE_CALL_STATS_VIDEO].received_rtcp != NULL)
1869                                         freemsg(call->stats[LINPHONE_CALL_STATS_VIDEO].received_rtcp);
1870                                 call->stats[LINPHONE_CALL_STATS_VIDEO].received_rtcp = evd->packet;
1871                                 evd->packet = NULL;
1872                                 if (lc->vtable.call_stats_updated)
1873                                         lc->vtable.call_stats_updated(lc, call, &call->stats[LINPHONE_CALL_STATS_VIDEO]);
1874                         } else if (evt == ORTP_EVENT_RTCP_PACKET_EMITTED) {
1875                                 memcpy(&call->stats[LINPHONE_CALL_STATS_VIDEO].jitter_stats, rtp_session_get_jitter_stats(call->videostream->session), sizeof(jitter_stats_t));
1876                                 if(call->stats[LINPHONE_CALL_STATS_VIDEO].sent_rtcp != NULL)
1877                                         freemsg(call->stats[LINPHONE_CALL_STATS_VIDEO].sent_rtcp);
1878                                 call->stats[LINPHONE_CALL_STATS_VIDEO].sent_rtcp = evd->packet;
1879                                 evd->packet = NULL;
1880                                 if (lc->vtable.call_stats_updated)
1881                                         lc->vtable.call_stats_updated(lc, call, &call->stats[LINPHONE_CALL_STATS_VIDEO]);
1882                         } else if ((evt == ORTP_EVENT_ICE_SESSION_PROCESSING_FINISHED) || (evt == ORTP_EVENT_ICE_GATHERING_FINISHED)
1883                                 || (evt == ORTP_EVENT_ICE_LOSING_PAIRS_COMPLETED) || (evt == ORTP_EVENT_ICE_RESTART_NEEDED)) {
1884                                 handle_ice_events(call, ev);
1885                         }
1886                         ortp_event_destroy(ev);
1887                 }
1888         }
1889 #endif
1890         if (call->audiostream!=NULL) {
1891                 OrtpEvent *ev;
1892
1893                 /* Ensure there is no dangling ICE check list. */
1894                 if (call->ice_session == NULL) call->audiostream->ice_check_list = NULL;
1895
1896                 // Beware that the application queue should not depend on treatments fron the
1897                 // mediastreamer queue.
1898                 audio_stream_iterate(call->audiostream);
1899
1900                 while (call->audiostream_app_evq && (NULL != (ev=ortp_ev_queue_get(call->audiostream_app_evq)))){
1901                         OrtpEventType evt=ortp_event_get_type(ev);
1902                         OrtpEventData *evd=ortp_event_get_data(ev);
1903                         if (evt == ORTP_EVENT_ZRTP_ENCRYPTION_CHANGED){
1904                                 linphone_call_audiostream_encryption_changed(call, evd->info.zrtp_stream_encrypted);
1905                         } else if (evt == ORTP_EVENT_ZRTP_SAS_READY) {
1906                                 linphone_call_audiostream_auth_token_ready(call, evd->info.zrtp_sas.sas, evd->info.zrtp_sas.verified);
1907                         } else if (evt == ORTP_EVENT_RTCP_PACKET_RECEIVED) {
1908                                 call->stats[LINPHONE_CALL_STATS_AUDIO].round_trip_delay = rtp_session_get_round_trip_propagation(call->audiostream->session);
1909                                 if(call->stats[LINPHONE_CALL_STATS_AUDIO].received_rtcp != NULL)
1910                                         freemsg(call->stats[LINPHONE_CALL_STATS_AUDIO].received_rtcp);
1911                                 call->stats[LINPHONE_CALL_STATS_AUDIO].received_rtcp = evd->packet;
1912                                 evd->packet = NULL;
1913                                 if (lc->vtable.call_stats_updated)
1914                                         lc->vtable.call_stats_updated(lc, call, &call->stats[LINPHONE_CALL_STATS_AUDIO]);
1915                         } else if (evt == ORTP_EVENT_RTCP_PACKET_EMITTED) {
1916                                 memcpy(&call->stats[LINPHONE_CALL_STATS_AUDIO].jitter_stats, rtp_session_get_jitter_stats(call->audiostream->session), sizeof(jitter_stats_t));
1917                                 if(call->stats[LINPHONE_CALL_STATS_AUDIO].sent_rtcp != NULL)
1918                                         freemsg(call->stats[LINPHONE_CALL_STATS_AUDIO].sent_rtcp);
1919                                 call->stats[LINPHONE_CALL_STATS_AUDIO].sent_rtcp = evd->packet;
1920                                 evd->packet = NULL;
1921                                 if (lc->vtable.call_stats_updated)
1922                                         lc->vtable.call_stats_updated(lc, call, &call->stats[LINPHONE_CALL_STATS_AUDIO]);
1923                         } else if ((evt == ORTP_EVENT_ICE_SESSION_PROCESSING_FINISHED) || (evt == ORTP_EVENT_ICE_GATHERING_FINISHED)
1924                                 || (evt == ORTP_EVENT_ICE_LOSING_PAIRS_COMPLETED) || (evt == ORTP_EVENT_ICE_RESTART_NEEDED)) {
1925                                 handle_ice_events(call, ev);
1926                         }
1927                         ortp_event_destroy(ev);
1928                 }
1929         }
1930         if (call->state==LinphoneCallStreamsRunning && one_second_elapsed && call->audiostream!=NULL && disconnect_timeout>0 )
1931                 disconnected=!audio_stream_alive(call->audiostream,disconnect_timeout);
1932         if (disconnected)
1933                 linphone_core_disconnected(call->core,call);
1934 }
1935
1936 void linphone_call_log_completed(LinphoneCall *call){
1937         LinphoneCore *lc=call->core;
1938
1939         call->log->duration=time(NULL)-call->start_time;
1940
1941         if (call->log->status==LinphoneCallMissed){
1942                 char *info;
1943                 lc->missed_calls++;
1944                 info=ortp_strdup_printf(ngettext("You have missed %i call.",
1945                                          "You have missed %i calls.", lc->missed_calls),
1946                                 lc->missed_calls);
1947         if (lc->vtable.display_status!=NULL)
1948             lc->vtable.display_status(lc,info);
1949                 ms_free(info);
1950         }
1951         lc->call_logs=ms_list_prepend(lc->call_logs,(void *)call->log);
1952         if (ms_list_size(lc->call_logs)>lc->max_call_logs){
1953                 MSList *elem,*prevelem=NULL;
1954                 /*find the last element*/
1955                 for(elem=lc->call_logs;elem!=NULL;elem=elem->next){
1956                         prevelem=elem;
1957                 }
1958                 elem=prevelem;
1959                 linphone_call_log_destroy((LinphoneCallLog*)elem->data);
1960                 lc->call_logs=ms_list_remove_link(lc->call_logs,elem);
1961         }
1962         if (lc->vtable.call_log_updated!=NULL){
1963                 lc->vtable.call_log_updated(lc,call->log);
1964         }
1965         call_logs_write_to_config_file(lc);
1966 }
1967
1968 LinphoneCallState linphone_call_get_transfer_state(LinphoneCall *call) {
1969         return call->transfer_state;
1970 }
1971
1972 void linphone_call_set_transfer_state(LinphoneCall* call, LinphoneCallState state) {
1973         if (state != call->transfer_state) {
1974                 LinphoneCore* lc = call->core;
1975                 call->transfer_state = state;
1976                 if (lc->vtable.transfer_state_changed)
1977                         lc->vtable.transfer_state_changed(lc, call, state);
1978         }
1979 }
1980
1981 bool_t linphone_call_is_in_conference(const LinphoneCall *call) {
1982         return call->params.in_conference;
1983 }