]> sjero.net Git - linphone/blob - coreapi/linphonecall.c
merge patch for notification bubbles + 2nd call incoming tone notification
[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
30
31 #include "mediastreamer2/mediastream.h"
32 #include "mediastreamer2/msvolume.h"
33 #include "mediastreamer2/msequalizer.h"
34 #include "mediastreamer2/msfileplayer.h"
35 #include "mediastreamer2/msjpegwriter.h"
36 #include "mediastreamer2/mseventqueue.h"
37
38 #ifdef VIDEO_ENABLED
39 static MSWebCam *get_nowebcam_device(){
40         return ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),"StaticImage: Static picture");
41 }
42 #endif
43
44 static const char* get_hexa_zrtp_identifier(LinphoneCore *lc){
45         const char *confZid=lp_config_get_string(lc->config,"rtp","zid",NULL);
46         if (confZid != NULL) {
47                 return confZid;
48         } else {
49         char zidstr[128];
50         snprintf(zidstr,sizeof(zidstr),"%x-%x-%x",rand(),rand(),rand());
51                 lp_config_set_string(lc->config,"rtp","zid",zidstr);
52                 return lp_config_get_string(lc->config,"rtp","zid",NULL);
53         }
54 }
55
56 const char* linphone_call_get_authentication_token(LinphoneCall *call){
57         return call->auth_token;
58 }
59
60 bool_t linphone_call_get_authentication_token_verified(LinphoneCall *call){
61         return call->auth_token_verified;
62 }
63 bool_t linphone_call_are_all_streams_encrypted(LinphoneCall *call) {
64         // Check ZRTP encryption in audiostream
65         if (!call->audiostream_encrypted) {
66                 return FALSE;
67         }
68
69 #ifdef VIDEO_ENABLED
70         // If video enabled, check ZRTP encryption in videostream
71         const LinphoneCallParams *params=linphone_call_get_current_params(call);
72         if (params->has_video && !call->videostream_encrypted) {
73                 return FALSE;
74         }
75 #endif
76
77         return TRUE;
78 }
79
80 void propagate_encryption_changed(LinphoneCall *call){
81         if (call->core->vtable.call_encryption_changed == NULL) return;
82
83         if (!linphone_call_are_all_streams_encrypted(call)) {
84                 ms_message("Some streams are not encrypted");
85                 call->core->vtable.call_encryption_changed(call->core, call, FALSE, call->auth_token);
86         } else {
87                 ms_message("All streams are encrypted");
88                 call->core->vtable.call_encryption_changed(call->core, call, TRUE, call->auth_token);
89         }
90 }
91
92 #ifdef VIDEO_ENABLED
93 static void linphone_call_videostream_encryption_changed(void *data, bool_t encrypted){
94         ms_message("Video stream is %s", encrypted ? "encrypted" : "not encrypted");
95
96         LinphoneCall *call = (LinphoneCall *)data;
97         call->videostream_encrypted=encrypted;
98         propagate_encryption_changed(call);
99 }
100 #endif
101
102 static void linphone_call_audiostream_encryption_changed(void *data, bool_t encrypted) {
103         char status[255]={0};
104         ms_message("Audio stream is %s ", encrypted ? "encrypted" : "not encrypted");
105
106         LinphoneCall *call = (LinphoneCall *)data;
107         call->audiostream_encrypted=encrypted;
108
109         if (encrypted && call->core->vtable.display_status != NULL) {
110                 snprintf(status,sizeof(status)-1,_("Authentication token is %s"),call->auth_token);
111                  call->core->vtable.display_status(call->core, status);
112         }
113
114         propagate_encryption_changed(call);
115
116
117 #ifdef VIDEO_ENABLED
118         // Enable video encryption
119         const LinphoneCallParams *params=linphone_call_get_current_params(call);
120         if (params->has_video) {
121                 ms_message("Trying to enable encryption on video stream");
122                 OrtpZrtpParams params;
123                 params.zid=get_hexa_zrtp_identifier(call->core);
124                 params.zid_file=NULL; //unused
125                 video_stream_enable_zrtp(call->videostream,call->audiostream,&params);
126         }
127 #endif
128 }
129
130
131 static void linphone_call_audiostream_auth_token_ready(void *data, const char* auth_token, bool_t verified) {
132         LinphoneCall *call=(LinphoneCall *)data;
133         if (call->auth_token != NULL)
134                 ms_free(call->auth_token);
135
136         call->auth_token=ms_strdup(auth_token);
137         call->auth_token_verified=verified;
138
139         ms_message("Authentication token is %s (%s)", auth_token, verified?"verified":"unverified");
140 }
141
142
143 static MSList *make_codec_list(LinphoneCore *lc, const MSList *codecs, int bandwidth_limit){
144         MSList *l=NULL;
145         const MSList *it;
146         for(it=codecs;it!=NULL;it=it->next){
147                 PayloadType *pt=(PayloadType*)it->data;
148                 if (pt->flags & PAYLOAD_TYPE_ENABLED){
149                         if (bandwidth_limit>0 && !linphone_core_is_payload_type_usable_for_bandwidth(lc,pt,bandwidth_limit)){
150                                 ms_message("Codec %s/%i eliminated because of audio bandwidth constraint.",pt->mime_type,pt->clock_rate);
151                                 continue;
152                         }
153                         if (linphone_core_check_payload_type_usability(lc,pt)){
154                                 l=ms_list_append(l,payload_type_clone(pt));
155                         }
156                 }
157         }
158         return l;
159 }
160
161 static SalMediaDescription *_create_local_media_description(LinphoneCore *lc, LinphoneCall *call, unsigned int session_id, unsigned int session_ver){
162         MSList *l;
163         PayloadType *pt;
164         const char *me=linphone_core_get_identity(lc);
165         LinphoneAddress *addr=linphone_address_new(me);
166         const char *username=linphone_address_get_username (addr);
167         SalMediaDescription *md=sal_media_description_new();
168         
169         md->session_id=session_id;
170         md->session_ver=session_ver;
171         md->nstreams=1;
172         strncpy(md->addr,call->localip,sizeof(md->addr));
173         strncpy(md->username,username,sizeof(md->username));
174         md->bandwidth=linphone_core_get_download_bandwidth(lc);
175         
176         /*set audio capabilities */
177         strncpy(md->streams[0].addr,call->localip,sizeof(md->streams[0].addr));
178         md->streams[0].port=call->audio_port;
179         md->streams[0].proto=SalProtoRtpAvp;
180         md->streams[0].type=SalAudio;
181         md->streams[0].ptime=lc->net_conf.down_ptime;
182         l=make_codec_list(lc,lc->codecs_conf.audio_codecs,call->params.audio_bw);
183         pt=payload_type_clone(rtp_profile_get_payload_from_mime(&av_profile,"telephone-event"));
184         l=ms_list_append(l,pt);
185         md->streams[0].payloads=l;
186         
187
188         if (call->params.has_video){
189                 md->nstreams++;
190                 md->streams[1].port=call->video_port;
191                 md->streams[1].proto=SalProtoRtpAvp;
192                 md->streams[1].type=SalVideo;
193                 l=make_codec_list(lc,lc->codecs_conf.video_codecs,0);
194                 md->streams[1].payloads=l;
195         }
196         linphone_address_destroy(addr);
197         return md;
198 }
199
200 void update_local_media_description(LinphoneCore *lc, LinphoneCall *call, SalMediaDescription **md){
201         if (*md == NULL) {
202                 *md = _create_local_media_description(lc,call,0,0);
203         } else {
204                 unsigned int id = (*md)->session_id;
205                 unsigned int ver = (*md)->session_ver+1;
206                 sal_media_description_unref(*md);
207                 *md = _create_local_media_description(lc,call,id,ver);
208         }
209 }
210
211 SalMediaDescription *create_local_media_description(LinphoneCore *lc, LinphoneCall *call){
212         unsigned int id=rand() & 0xfff;
213         return _create_local_media_description(lc,call,id,id);
214 }
215
216 static int find_port_offset(LinphoneCore *lc){
217         int offset;
218         MSList *elem;
219         int audio_port;
220         bool_t already_used=FALSE;
221         for(offset=0;offset<100;offset+=2){
222                 audio_port=linphone_core_get_audio_port (lc)+offset;
223                 already_used=FALSE;
224                 for(elem=lc->calls;elem!=NULL;elem=elem->next){
225                         LinphoneCall *call=(LinphoneCall*)elem->data;
226                         if (call->audio_port==audio_port) {
227                                 already_used=TRUE;
228                                 break;
229                         }
230                 }
231                 if (!already_used) break;
232         }
233         if (offset==100){
234                 ms_error("Could not find any free port !");
235                 return -1;
236         }
237         return offset;
238 }
239
240 static void linphone_call_init_common(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
241         int port_offset;
242         call->refcnt=1;
243         call->state=LinphoneCallIdle;
244         call->start_time=time(NULL);
245         call->media_start_time=0;
246         call->log=linphone_call_log_new(call, from, to);
247         call->owns_call_log=TRUE;
248         linphone_core_notify_all_friends(call->core,LinphoneStatusOnThePhone);
249         port_offset=find_port_offset (call->core);
250         if (port_offset==-1) return;
251         call->audio_port=linphone_core_get_audio_port(call->core)+port_offset;
252         call->video_port=linphone_core_get_video_port(call->core)+port_offset;
253         
254 }
255
256 static void discover_mtu(LinphoneCore *lc, const char *remote){
257         int mtu;
258         if (lc->net_conf.mtu==0 ){
259                 /*attempt to discover mtu*/
260                 mtu=ms_discover_mtu(remote);
261                 if (mtu>0){
262                         ms_set_mtu(mtu);
263                         ms_message("Discovered mtu is %i, RTP payload max size is %i",
264                                 mtu, ms_get_payload_max_size());
265                 }
266         }
267 }
268
269 LinphoneCall * linphone_call_new_outgoing(struct _LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, const LinphoneCallParams *params)
270 {
271         LinphoneCall *call=ms_new0(LinphoneCall,1);
272         call->dir=LinphoneCallOutgoing;
273         call->op=sal_op_new(lc->sal);
274         sal_op_set_user_pointer(call->op,call);
275         call->core=lc;
276         linphone_core_get_local_ip(lc,linphone_address_get_domain(to),call->localip);
277         linphone_call_init_common(call,from,to);
278         call->params=*params;
279         call->localdesc=create_local_media_description (lc,call);
280         call->camera_active=params->has_video;
281         if (linphone_core_get_firewall_policy(call->core)==LinphonePolicyUseStun)
282                 linphone_core_run_stun_tests(call->core,call);
283         discover_mtu(lc,linphone_address_get_domain (to));
284         if (params->referer){
285                 sal_call_set_referer (call->op,params->referer->op);
286         }
287         return call;
288 }
289
290 LinphoneCall * linphone_call_new_incoming(LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, SalOp *op){
291         LinphoneCall *call=ms_new0(LinphoneCall,1);
292         char *from_str;
293
294         call->dir=LinphoneCallIncoming;
295         sal_op_set_user_pointer(op,call);
296         call->op=op;
297         call->core=lc;
298
299         if (lc->sip_conf.ping_with_options){
300                 /*the following sends an option request back to the caller so that
301                  we get a chance to discover our nat'd address before answering.*/
302                 call->ping_op=sal_op_new(lc->sal);
303                 from_str=linphone_address_as_string(from);
304                 sal_op_set_route(call->ping_op,sal_op_get_network_origin(call->op));
305                 sal_op_set_user_pointer(call->ping_op,call);
306                 sal_ping(call->ping_op,linphone_core_find_best_identity(lc,from,NULL),from_str);
307                 ms_free(from_str);
308         }
309         
310         linphone_address_clean(from);
311         linphone_core_get_local_ip(lc,linphone_address_get_domain(from),call->localip);
312         linphone_call_init_common(call, from, to);
313         call->params.has_video=linphone_core_video_enabled(lc);
314         call->localdesc=create_local_media_description (lc,call);
315         call->camera_active=call->params.has_video;
316         if (linphone_core_get_firewall_policy(call->core)==LinphonePolicyUseStun)
317                 linphone_core_run_stun_tests(call->core,call);
318         discover_mtu(lc,linphone_address_get_domain(from));
319         return call;
320 }
321
322 /* this function is called internally to get rid of a call.
323  It performs the following tasks:
324  - remove the call from the internal list of calls
325  - update the call logs accordingly
326 */
327
328 static void linphone_call_set_terminated(LinphoneCall *call){
329         LinphoneCore *lc=call->core;
330         
331         linphone_core_update_allocated_audio_bandwidth(lc);
332
333         call->owns_call_log=FALSE;
334         linphone_call_log_completed(call);
335         
336         
337         if (call == lc->current_call){
338                 ms_message("Resetting the current call");
339                 lc->current_call=NULL;
340         }
341
342         if (linphone_core_del_call(lc,call) != 0){
343                 ms_error("Could not remove the call from the list !!!");
344         }
345         
346         if (ms_list_size(lc->calls)==0)
347                 linphone_core_notify_all_friends(lc,lc->presence_mode);
348         
349 }
350
351 const char *linphone_call_state_to_string(LinphoneCallState cs){
352         switch (cs){
353                 case LinphoneCallIdle:
354                         return "LinphoneCallIdle";
355                 case LinphoneCallIncomingReceived:
356                         return "LinphoneCallIncomingReceived";
357                 case LinphoneCallOutgoingInit:
358                         return "LinphoneCallOutgoingInit";
359                 case LinphoneCallOutgoingProgress:
360                         return "LinphoneCallOutgoingProgress";
361                 case LinphoneCallOutgoingRinging:
362                         return "LinphoneCallOutgoingRinging";
363                 case LinphoneCallOutgoingEarlyMedia:
364                         return "LinphoneCallOutgoingEarlyMedia";
365                 case LinphoneCallConnected:
366                         return "LinphoneCallConnected";
367                 case LinphoneCallStreamsRunning:
368                         return "LinphoneCallStreamsRunning";
369                 case LinphoneCallPausing:
370                         return "LinphoneCallPausing";
371                 case LinphoneCallPaused:
372                         return "LinphoneCallPaused";
373                 case LinphoneCallResuming:
374                         return "LinphoneCallResuming";
375                 case LinphoneCallRefered:
376                         return "LinphoneCallRefered";
377                 case LinphoneCallError:
378                         return "LinphoneCallError";
379                 case LinphoneCallEnd:
380                         return "LinphoneCallEnd";
381                 case LinphoneCallPausedByRemote:
382                         return "LinphoneCallPausedByRemote";
383                 case LinphoneCallUpdatedByRemote:
384                         return "LinphoneCallUpdatedByRemote";
385                 case LinphoneCallIncomingEarlyMedia:
386                         return "LinphoneCallIncomingEarlyMedia";
387                 case LinphoneCallUpdated:
388                         return "LinphoneCallUpdated";
389                 case LinphoneCallReleased:
390                         return "LinphoneCallReleased";
391         }
392         return "undefined state";
393 }
394
395 void linphone_call_set_state(LinphoneCall *call, LinphoneCallState cstate, const char *message){
396         LinphoneCore *lc=call->core;
397
398         if (call->state!=cstate){
399                 if (call->state==LinphoneCallEnd || call->state==LinphoneCallError){
400                         if (cstate!=LinphoneCallReleased){
401                                 ms_warning("Spurious call state change from %s to %s, ignored.",linphone_call_state_to_string(call->state),
402                            linphone_call_state_to_string(cstate));
403                                 return;
404                         }
405                 }
406                 ms_message("Call %p: moving from state %s to %s",call,linphone_call_state_to_string(call->state),
407                            linphone_call_state_to_string(cstate));
408                 if (cstate!=LinphoneCallRefered){
409                         /*LinphoneCallRefered is rather an event, not a state.
410                          Indeed it does not change the state of the call (still paused or running)*/
411                         call->state=cstate;
412                 }
413                 if (cstate==LinphoneCallEnd || cstate==LinphoneCallError){
414              if (call->reason==LinphoneReasonDeclined){
415                  call->log->status=LinphoneCallDeclined;
416              }
417             linphone_call_set_terminated (call);
418                 }
419         if (cstate == LinphoneCallConnected) {
420             call->log->status=LinphoneCallSuccess;
421         }
422                 
423                 if (lc->vtable.call_state_changed)
424                         lc->vtable.call_state_changed(lc,call,cstate,message);
425                 if (cstate==LinphoneCallReleased){
426                         if (call->op!=NULL) {
427                                 /* so that we cannot have anymore upcalls for SAL
428                                  concerning this call*/
429                                 sal_op_release(call->op);
430                                 call->op=NULL;
431                         }
432                         linphone_call_unref(call);
433                 }
434         }
435 }
436
437 static void linphone_call_destroy(LinphoneCall *obj)
438 {
439         if (obj->op!=NULL) {
440                 sal_op_release(obj->op);
441                 obj->op=NULL;
442         }
443         if (obj->resultdesc!=NULL) {
444                 sal_media_description_unref(obj->resultdesc);
445                 obj->resultdesc=NULL;
446         }
447         if (obj->localdesc!=NULL) {
448                 sal_media_description_unref(obj->localdesc);
449                 obj->localdesc=NULL;
450         }
451         if (obj->ping_op) {
452                 sal_op_release(obj->ping_op);
453         }
454         if (obj->refer_to){
455                 ms_free(obj->refer_to);
456         }
457         if (obj->owns_call_log)
458                 linphone_call_log_destroy(obj->log);
459         if (obj->auth_token) {
460                 ms_free(obj->auth_token);
461         }
462
463         ms_free(obj);
464 }
465
466 /**
467  * @addtogroup call_control
468  * @{
469 **/
470
471 /**
472  * Increments the call 's reference count.
473  * An application that wishes to retain a pointer to call object
474  * must use this function to unsure the pointer remains
475  * valid. Once the application no more needs this pointer,
476  * it must call linphone_call_unref().
477 **/
478 void linphone_call_ref(LinphoneCall *obj){
479         obj->refcnt++;
480 }
481
482 /**
483  * Decrements the call object reference count.
484  * See linphone_call_ref().
485 **/
486 void linphone_call_unref(LinphoneCall *obj){
487         obj->refcnt--;
488         if (obj->refcnt==0){
489                 linphone_call_destroy(obj);
490         }
491 }
492
493 /**
494  * Returns current parameters associated to the call.
495 **/
496 const LinphoneCallParams * linphone_call_get_current_params(const LinphoneCall *call){
497         return &call->current_params;
498 }
499
500 /**
501  * Returns the remote address associated to this call
502  *
503 **/
504 const LinphoneAddress * linphone_call_get_remote_address(const LinphoneCall *call){
505         return call->dir==LinphoneCallIncoming ? call->log->from : call->log->to;
506 }
507
508 /**
509  * Returns the remote address associated to this call as a string.
510  *
511  * The result string must be freed by user using ms_free().
512 **/
513 char *linphone_call_get_remote_address_as_string(const LinphoneCall *call){
514         return linphone_address_as_string(linphone_call_get_remote_address(call));
515 }
516
517 /**
518  * Retrieves the call's current state.
519 **/
520 LinphoneCallState linphone_call_get_state(const LinphoneCall *call){
521         return call->state;
522 }
523
524 /**
525  * Returns the reason for a call termination (either error or normal termination)
526 **/
527 LinphoneReason linphone_call_get_reason(const LinphoneCall *call){
528         return call->reason;
529 }
530
531 /**
532  * Get the user_pointer in the LinphoneCall
533  *
534  * @ingroup call_control
535  *
536  * return user_pointer an opaque user pointer that can be retrieved at any time
537 **/
538 void *linphone_call_get_user_pointer(LinphoneCall *call)
539 {
540         return call->user_pointer;
541 }
542
543 /**
544  * Set the user_pointer in the LinphoneCall
545  *
546  * @ingroup call_control
547  *
548  * the user_pointer is an opaque user pointer that can be retrieved at any time in the LinphoneCall
549 **/
550 void linphone_call_set_user_pointer(LinphoneCall *call, void *user_pointer)
551 {
552         call->user_pointer = user_pointer;
553 }
554
555 /**
556  * Returns the call log associated to this call.
557 **/
558 LinphoneCallLog *linphone_call_get_call_log(const LinphoneCall *call){
559         return call->log;
560 }
561
562 /**
563  * Returns the refer-to uri (if the call was transfered).
564 **/
565 const char *linphone_call_get_refer_to(const LinphoneCall *call){
566         return call->refer_to;
567 }
568
569 /**
570  * Returns direction of the call (incoming or outgoing).
571 **/
572 LinphoneCallDir linphone_call_get_dir(const LinphoneCall *call){
573         return call->log->dir;
574 }
575
576 /**
577  * Returns the far end's user agent description string, if available.
578 **/
579 const char *linphone_call_get_remote_user_agent(LinphoneCall *call){
580         if (call->op){
581                 return sal_op_get_remote_ua (call->op);
582         }
583         return NULL;
584 }
585
586 /**
587  * Returns true if this calls has received a transfer that has not been
588  * executed yet.
589  * Pending transfers are executed when this call is being paused or closed,
590  * locally or by remote endpoint.
591  * If the call is already paused while receiving the transfer request, the 
592  * transfer immediately occurs.
593 **/
594 bool_t linphone_call_has_transfer_pending(const LinphoneCall *call){
595         return call->refer_pending;
596 }
597
598 /**
599  * Returns call's duration in seconds.
600 **/
601 int linphone_call_get_duration(const LinphoneCall *call){
602         if (call->media_start_time==0) return 0;
603         return time(NULL)-call->media_start_time;
604 }
605
606 /**
607  * Returns the call object this call is replacing, if any.
608  * Call replacement can occur during call transfers.
609  * By default, the core automatically terminates the replaced call and accept the new one.
610  * This function allows the application to know whether a new incoming call is a one that replaces another one.
611 **/
612 LinphoneCall *linphone_call_get_replaced_call(LinphoneCall *call){
613         SalOp *op=sal_call_get_replaces(call->op);
614         if (op){
615                 return (LinphoneCall*)sal_op_get_user_pointer(op);
616         }
617         return NULL;
618 }
619
620 /**
621  * Indicate whether camera input should be sent to remote end.
622 **/
623 void linphone_call_enable_camera (LinphoneCall *call, bool_t enable){
624 #ifdef VIDEO_ENABLED
625         if (call->videostream!=NULL && call->videostream->ticker!=NULL){
626                 LinphoneCore *lc=call->core;
627                 MSWebCam *nowebcam=get_nowebcam_device();
628                 if (call->camera_active!=enable && lc->video_conf.device!=nowebcam){
629                         video_stream_change_camera(call->videostream,
630                                      enable ? lc->video_conf.device : nowebcam);
631                 }
632         }
633         call->camera_active=enable;
634 #endif
635 }
636
637 /**
638  * Take a photo of currently received video and write it into a jpeg file.
639 **/
640 int linphone_call_take_video_snapshot(LinphoneCall *call, const char *file){
641 #ifdef VIDEO_ENABLED
642         if (call->videostream!=NULL && call->videostream->jpegwriter!=NULL){
643                 return ms_filter_call_method(call->videostream->jpegwriter,MS_JPEG_WRITER_TAKE_SNAPSHOT,(void*)file);
644         }
645         ms_warning("Cannot take snapshot: no currently running video stream on this call.");
646         return -1;
647 #endif
648         return -1;
649 }
650
651 /**
652  * Returns TRUE if camera pictures are sent to the remote party.
653 **/
654 bool_t linphone_call_camera_enabled (const LinphoneCall *call){
655         return call->camera_active;
656 }
657
658 /**
659  * Enable video stream.
660 **/
661 void linphone_call_params_enable_video(LinphoneCallParams *cp, bool_t enabled){
662         cp->has_video=enabled;
663 }
664
665 /**
666  * Returns whether video is enabled.
667 **/
668 bool_t linphone_call_params_video_enabled(const LinphoneCallParams *cp){
669         return cp->has_video;
670 }
671
672 /**
673  * Enable sending of real early media (during outgoing calls).
674 **/
675 void linphone_call_params_enable_early_media_sending(LinphoneCallParams *cp, bool_t enabled){
676         cp->real_early_media=enabled;
677 }
678
679 bool_t linphone_call_params_early_media_sending_enabled(const LinphoneCallParams *cp){
680         return cp->real_early_media;
681 }
682
683 /**
684  * Returns true if the call is part of the locally managed conference.
685 **/
686 bool_t linphone_call_params_local_conference_mode(const LinphoneCallParams *cp){
687         return cp->in_conference;
688 }
689
690 /**
691  * Refine bandwidth settings for this call by setting a bandwidth limit for audio streams.
692  * As a consequence, codecs whose bitrates are not compatible with this limit won't be used.
693 **/
694 void linphone_call_params_set_audio_bandwidth_limit(LinphoneCallParams *cp, int bandwidth){
695         cp->audio_bw=bandwidth;
696 }
697
698 #ifdef VIDEO_ENABLED
699 /**
700  * Request remote side to send us a Video Fast Update.
701 **/
702 void linphone_call_send_vfu_request(LinphoneCall *call)
703 {
704         if (LinphoneCallStreamsRunning == linphone_call_get_state(call))
705                 sal_call_send_vfu_request(call->op);
706 }
707 #endif
708
709 /**
710  *
711 **/
712 LinphoneCallParams * linphone_call_params_copy(const LinphoneCallParams *cp){
713         LinphoneCallParams *ncp=ms_new0(LinphoneCallParams,1);
714         memcpy(ncp,cp,sizeof(LinphoneCallParams));
715         return ncp;
716 }
717
718 /**
719  *
720 **/
721 void linphone_call_params_destroy(LinphoneCallParams *p){
722         ms_free(p);
723 }
724
725 /**
726  * @}
727 **/
728
729
730 #ifdef TEST_EXT_RENDERER
731 static void rendercb(void *data, const MSPicture *local, const MSPicture *remote){
732         ms_message("rendercb, local buffer=%p, remote buffer=%p",
733                    local ? local->planes[0] : NULL, remote? remote->planes[0] : NULL);
734 }
735 #endif
736
737 #ifdef VIDEO_ENABLED
738 static void video_stream_event_cb(void *user_pointer, const MSFilter *f, const unsigned int event_id, const void *args){
739         ms_warning("In linphonecall.c: video_stream_event_cb");
740         switch (event_id) {
741                 case MS_VIDEO_DECODER_DECODING_ERRORS:
742                         ms_warning("Case is MS_VIDEO_DECODER_DECODING_ERRORS");
743                         linphone_call_send_vfu_request((LinphoneCall*) user_pointer);
744                         break;
745                 default:
746                         ms_warning("Unhandled event %i", event_id);
747                         break;
748         }
749 }
750 #endif
751
752 void linphone_call_init_media_streams(LinphoneCall *call){
753         LinphoneCore *lc=call->core;
754         SalMediaDescription *md=call->localdesc;
755         AudioStream *audiostream;
756         
757         call->audiostream=audiostream=audio_stream_new(md->streams[0].port,linphone_core_ipv6_enabled(lc));
758         if (linphone_core_echo_limiter_enabled(lc)){
759                 const char *type=lp_config_get_string(lc->config,"sound","el_type","mic");
760                 if (strcasecmp(type,"mic")==0)
761                         audio_stream_enable_echo_limiter(audiostream,ELControlMic);
762                 else if (strcasecmp(type,"full")==0)
763                         audio_stream_enable_echo_limiter(audiostream,ELControlFull);
764         }
765         audio_stream_enable_gain_control(audiostream,TRUE);
766         if (linphone_core_echo_cancellation_enabled(lc)){
767                 int len,delay,framesize;
768                 const char *statestr=lp_config_get_string(lc->config,"sound","ec_state",NULL);
769                 len=lp_config_get_int(lc->config,"sound","ec_tail_len",0);
770                 delay=lp_config_get_int(lc->config,"sound","ec_delay",0);
771                 framesize=lp_config_get_int(lc->config,"sound","ec_framesize",0);
772                 audio_stream_set_echo_canceller_params(audiostream,len,delay,framesize);
773                 if (statestr && audiostream->ec){
774                         ms_filter_call_method(audiostream->ec,MS_ECHO_CANCELLER_SET_STATE_STRING,(void*)statestr);
775                 }
776         }
777         audio_stream_enable_automatic_gain_control(audiostream,linphone_core_agc_enabled(lc));
778         {
779                 int enabled=lp_config_get_int(lc->config,"sound","noisegate",0);
780                 audio_stream_enable_noise_gate(audiostream,enabled);
781         }
782         
783         if (lc->a_rtp)
784                 rtp_session_set_transports(audiostream->session,lc->a_rtp,lc->a_rtcp);
785
786         call->audiostream_app_evq = ortp_ev_queue_new();
787         rtp_session_register_event_queue(audiostream->session,call->audiostream_app_evq);
788
789 #ifdef VIDEO_ENABLED
790
791         if ((lc->video_conf.display || lc->video_conf.capture) && md->streams[1].port>0){
792                 call->videostream=video_stream_new(md->streams[1].port,linphone_core_ipv6_enabled(lc));
793         if( lc->video_conf.displaytype != NULL)
794                 video_stream_set_display_filter_name(call->videostream,lc->video_conf.displaytype);
795         video_stream_set_event_callback(call->videostream,video_stream_event_cb, call);
796         if (lc->v_rtp)
797                 rtp_session_set_transports(call->videostream->session,lc->v_rtp,lc->v_rtcp);
798         call->videostream_app_evq = ortp_ev_queue_new();
799         rtp_session_register_event_queue(call->videostream->session,call->videostream_app_evq);
800 #ifdef TEST_EXT_RENDERER
801                 video_stream_set_render_callback(call->videostream,rendercb,NULL);
802 #endif
803         }
804 #else
805         call->videostream=NULL;
806 #endif
807 }
808
809
810 static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'};
811
812 static void linphone_core_dtmf_received(RtpSession* s, int dtmf, void* user_data){
813         LinphoneCore* lc = (LinphoneCore*)user_data;
814         if (dtmf<0 || dtmf>15){
815                 ms_warning("Bad dtmf value %i",dtmf);
816                 return;
817         }
818         if (lc->vtable.dtmf_received != NULL)
819                 lc->vtable.dtmf_received(lc, linphone_core_get_current_call(lc), dtmf_tab[dtmf]);
820 }
821
822 static void parametrize_equalizer(LinphoneCore *lc, AudioStream *st){
823         if (st->equalizer){
824                 MSFilter *f=st->equalizer;
825                 int enabled=lp_config_get_int(lc->config,"sound","eq_active",0);
826                 const char *gains=lp_config_get_string(lc->config,"sound","eq_gains",NULL);
827                 ms_filter_call_method(f,MS_EQUALIZER_SET_ACTIVE,&enabled);
828                 if (enabled){
829                         if (gains){
830                                 do{
831                                         int bytes;
832                                         MSEqualizerGain g;
833                                         if (sscanf(gains,"%f:%f:%f %n",&g.frequency,&g.gain,&g.width,&bytes)==3){
834                                                 ms_message("Read equalizer gains: %f(~%f) --> %f",g.frequency,g.width,g.gain);
835                                                 ms_filter_call_method(f,MS_EQUALIZER_SET_GAIN,&g);
836                                                 gains+=bytes;
837                                         }else break;
838                                 }while(1);
839                         }
840                 }
841         }
842 }
843
844 void _post_configure_audio_stream(AudioStream *st, LinphoneCore *lc, bool_t muted){
845         float mic_gain=lp_config_get_float(lc->config,"sound","mic_gain",1);
846         float thres = 0;
847         float recv_gain;
848         float ng_thres=lp_config_get_float(lc->config,"sound","ng_thres",0.05);
849         float ng_floorgain=lp_config_get_float(lc->config,"sound","ng_floorgain",0);
850         int dc_removal=lp_config_get_int(lc->config,"sound","dc_removal",0);
851         
852         if (!muted)
853                 audio_stream_set_mic_gain(st,mic_gain);
854         else 
855                 audio_stream_set_mic_gain(st,0);
856
857         recv_gain = lc->sound_conf.soft_play_lev;
858         if (recv_gain != 0) {
859                 linphone_core_set_playback_gain_db (lc,recv_gain);
860         }
861         if (st->volsend){
862                 ms_filter_call_method(st->volsend,MS_VOLUME_REMOVE_DC,&dc_removal);
863                 float speed=lp_config_get_float(lc->config,"sound","el_speed",-1);
864                 thres=lp_config_get_float(lc->config,"sound","el_thres",-1);
865                 float force=lp_config_get_float(lc->config,"sound","el_force",-1);
866                 int sustain=lp_config_get_int(lc->config,"sound","el_sustain",-1);
867                 float transmit_thres=lp_config_get_float(lc->config,"sound","el_transmit_thres",-1);
868                 MSFilter *f=NULL;
869                 f=st->volsend;
870                 if (speed==-1) speed=0.03;
871                 if (force==-1) force=25;
872                 ms_filter_call_method(f,MS_VOLUME_SET_EA_SPEED,&speed);
873                 ms_filter_call_method(f,MS_VOLUME_SET_EA_FORCE,&force);
874                 if (thres!=-1)
875                         ms_filter_call_method(f,MS_VOLUME_SET_EA_THRESHOLD,&thres);
876                 if (sustain!=-1)
877                         ms_filter_call_method(f,MS_VOLUME_SET_EA_SUSTAIN,&sustain);
878                 if (transmit_thres!=-1)
879                                 ms_filter_call_method(f,MS_VOLUME_SET_EA_TRANSMIT_THRESHOLD,&transmit_thres);
880
881                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_thres);
882                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&ng_floorgain);
883         }
884         if (st->volrecv){
885                 /* parameters for a limited noise-gate effect, using echo limiter threshold */
886                 float floorgain = 1/mic_gain;
887                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&thres);
888                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&floorgain);
889         }
890         parametrize_equalizer(lc,st);
891 }
892
893 static void post_configure_audio_streams(LinphoneCall*call){
894         AudioStream *st=call->audiostream;
895         LinphoneCore *lc=call->core;
896         _post_configure_audio_stream(st,lc,call->audio_muted);
897         if (lc->vtable.dtmf_received!=NULL){
898                 /* replace by our default action*/
899                 audio_stream_play_received_dtmfs(call->audiostream,FALSE);
900                 rtp_session_signal_connect(call->audiostream->session,"telephone-event",(RtpCallback)linphone_core_dtmf_received,(unsigned long)lc);
901         }
902 }
903
904 static RtpProfile *make_profile(LinphoneCall *call, const SalMediaDescription *md, const SalStreamDescription *desc, int *used_pt){
905         int bw;
906         const MSList *elem;
907         RtpProfile *prof=rtp_profile_new("Call profile");
908         bool_t first=TRUE;
909         int remote_bw=0;
910         LinphoneCore *lc=call->core;
911         int up_ptime=0;
912         *used_pt=-1;
913         
914         for(elem=desc->payloads;elem!=NULL;elem=elem->next){
915                 PayloadType *pt=(PayloadType*)elem->data;
916                 int number;
917                 
918                 if ((pt->flags & PAYLOAD_TYPE_FLAG_CAN_SEND) && first) {
919                         if (desc->type==SalAudio){
920                                 linphone_core_update_allocated_audio_bandwidth_in_call(call,pt);
921                                 up_ptime=linphone_core_get_upload_ptime(lc);
922                         }
923                         *used_pt=payload_type_get_number(pt);
924                         first=FALSE;
925                 }
926                 if (desc->bandwidth>0) remote_bw=desc->bandwidth;
927                 else if (md->bandwidth>0) {
928                         /*case where b=AS is given globally, not per stream*/
929                         remote_bw=md->bandwidth;
930                         if (desc->type==SalVideo){
931                                 remote_bw=get_video_bandwidth(remote_bw,call->audio_bw);
932                         }
933                 }
934                 
935                 if (desc->type==SalAudio){                      
936                                 bw=get_min_bandwidth(call->audio_bw,remote_bw);
937                 }else bw=get_min_bandwidth(get_video_bandwidth(linphone_core_get_upload_bandwidth (lc),call->audio_bw),remote_bw);
938                 if (bw>0) pt->normal_bitrate=bw*1000;
939                 else if (desc->type==SalAudio){
940                         pt->normal_bitrate=-1;
941                 }
942                 if (desc->ptime>0){
943                         up_ptime=desc->ptime;
944                 }
945                 if (up_ptime>0){
946                         char tmp[40];
947                         snprintf(tmp,sizeof(tmp),"ptime=%i",up_ptime);
948                         payload_type_append_send_fmtp(pt,tmp);
949                 }
950                 number=payload_type_get_number(pt);
951                 if (rtp_profile_get_payload(prof,number)!=NULL){
952                         ms_warning("A payload type with number %i already exists in profile !",number);
953                 }else
954                         rtp_profile_set_payload(prof,number,pt);
955         }
956         return prof;
957 }
958
959
960 static void setup_ring_player(LinphoneCore *lc, LinphoneCall *call){
961         int pause_time=3000;
962         audio_stream_play(call->audiostream,lc->sound_conf.ringback_tone);
963         ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
964 }
965
966 #define LINPHONE_RTCP_SDES_TOOL "Linphone-" LINPHONE_VERSION
967
968 static void linphone_call_start_audio_stream(LinphoneCall *call, const char *cname, bool_t muted, bool_t send_ringbacktone, bool_t use_arc){
969         LinphoneCore *lc=call->core;
970         int jitt_comp=lc->rtp_conf.audio_jitt_comp;
971         int used_pt=-1;
972         const SalStreamDescription *stream=sal_media_description_find_stream(call->resultdesc,
973                                                 SalProtoRtpAvp,SalAudio);
974         
975         if (stream && stream->dir!=SalStreamInactive && stream->port!=0){
976                 MSSndCard *playcard=lc->sound_conf.lsd_card ? 
977                         lc->sound_conf.lsd_card : lc->sound_conf.play_sndcard;
978                 MSSndCard *captcard=lc->sound_conf.capt_sndcard;
979                 const char *playfile=lc->play_file;
980                 const char *recfile=lc->rec_file;
981                 call->audio_profile=make_profile(call,call->resultdesc,stream,&used_pt);
982                 bool_t use_ec;
983
984                 if (used_pt!=-1){
985                         if (playcard==NULL) {
986                                 ms_warning("No card defined for playback !");
987                         }
988                         if (captcard==NULL) {
989                                 ms_warning("No card defined for capture !");
990                         }
991                         /*Replace soundcard filters by inactive file players or recorders
992                          when placed in recvonly or sendonly mode*/
993                         if (stream->port==0 || stream->dir==SalStreamRecvOnly){
994                                 captcard=NULL;
995                                 playfile=NULL;
996                         }else if (stream->dir==SalStreamSendOnly){
997                                 playcard=NULL;
998                                 captcard=NULL;
999                                 recfile=NULL;
1000                                 /*And we will eventually play "playfile" if set by the user*/
1001                                 /*playfile=NULL;*/
1002                         }
1003                         if (send_ringbacktone){
1004                                 captcard=NULL;
1005                                 playfile=NULL;/* it is setup later*/
1006                         }
1007                         /*if playfile are supplied don't use soundcards*/
1008                         if (lc->use_files) {
1009                                 captcard=NULL;
1010                                 playcard=NULL;
1011                         }
1012                         if (call->params.in_conference){
1013                                 /* first create the graph without soundcard resources*/
1014                                 captcard=playcard=NULL;
1015                         }
1016                         use_ec=captcard==NULL ? FALSE : linphone_core_echo_cancellation_enabled(lc);
1017
1018                         audio_stream_enable_adaptive_bitrate_control(call->audiostream,use_arc);
1019                         audio_stream_start_full(
1020                                 call->audiostream,
1021                                 call->audio_profile,
1022                                 stream->addr[0]!='\0' ? stream->addr : call->resultdesc->addr,
1023                                 stream->port,
1024                                 stream->port+1,
1025                                 used_pt,
1026                                 jitt_comp,
1027                                 playfile,
1028                                 recfile,
1029                                 playcard,
1030                                 captcard,
1031                                 use_ec
1032                                 );
1033                         post_configure_audio_streams(call);
1034                         if (muted && !send_ringbacktone){
1035                                 audio_stream_set_mic_gain(call->audiostream,0);
1036                         }
1037                         if (stream->dir==SalStreamSendOnly && playfile!=NULL){
1038                                 int pause_time=500;
1039                                 ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
1040                         }
1041                         if (send_ringbacktone){
1042                                 setup_ring_player(lc,call);
1043                         }
1044                         audio_stream_set_rtcp_information(call->audiostream, cname, LINPHONE_RTCP_SDES_TOOL);
1045                         if (call->params.in_conference){
1046                                 /*transform the graph to connect it to the conference filter */
1047                                 linphone_call_add_to_conf(call);
1048                         }
1049                 }else ms_warning("No audio stream accepted ?");
1050         }       
1051 }
1052
1053 static void linphone_call_start_video_stream(LinphoneCall *call, const char *cname,bool_t all_inputs_muted){
1054 #ifdef VIDEO_ENABLED
1055         LinphoneCore *lc=call->core;
1056         int used_pt=-1;
1057         const SalStreamDescription *vstream=sal_media_description_find_stream(call->resultdesc,
1058                                                         SalProtoRtpAvp,SalVideo);
1059         /* shutdown preview */
1060         if (lc->previewstream!=NULL) {
1061                 video_preview_stop(lc->previewstream);
1062                 lc->previewstream=NULL;
1063         }
1064         call->current_params.has_video=FALSE;
1065         if (vstream && vstream->dir!=SalStreamInactive && vstream->port!=0) {
1066                 const char *addr=vstream->addr[0]!='\0' ? vstream->addr : call->resultdesc->addr;
1067                 call->video_profile=make_profile(call,call->resultdesc,vstream,&used_pt);
1068                 if (used_pt!=-1){
1069                         VideoStreamDir dir=VideoStreamSendRecv;
1070                         MSWebCam *cam=lc->video_conf.device;
1071                         bool_t is_inactive=FALSE;
1072
1073                         call->current_params.has_video=TRUE;
1074                         
1075                         video_stream_set_sent_video_size(call->videostream,linphone_core_get_preferred_video_size(lc));
1076                         video_stream_enable_self_view(call->videostream,lc->video_conf.selfview);
1077                         if (lc->video_window_id!=0)
1078                                 video_stream_set_native_window_id(call->videostream,lc->video_window_id);
1079                         if (lc->preview_window_id!=0)
1080                                 video_stream_set_native_preview_window_id (call->videostream,lc->preview_window_id);
1081                         video_stream_use_preview_video_window (call->videostream,lc->use_preview_window);
1082                         
1083                         if (vstream->dir==SalStreamSendOnly && lc->video_conf.capture ){
1084                                 cam=get_nowebcam_device();
1085                                 dir=VideoStreamSendOnly;
1086                         }else if (vstream->dir==SalStreamRecvOnly && lc->video_conf.display ){
1087                                 dir=VideoStreamRecvOnly;
1088                         }else if (vstream->dir==SalStreamSendRecv){
1089                                 if (lc->video_conf.display && lc->video_conf.capture)
1090                                         dir=VideoStreamSendRecv;
1091                                 else if (lc->video_conf.display)
1092                                         dir=VideoStreamRecvOnly;
1093                                 else
1094                                         dir=VideoStreamSendOnly;
1095                         }else{
1096                                 ms_warning("video stream is inactive.");
1097                                 /*either inactive or incompatible with local capabilities*/
1098                                 is_inactive=TRUE;
1099                         }
1100                         if (call->camera_active==FALSE || all_inputs_muted){
1101                                 cam=get_nowebcam_device();
1102                         }
1103                         if (!is_inactive){
1104                                 video_stream_set_direction (call->videostream, dir);
1105                                 video_stream_start(call->videostream,
1106                                         call->video_profile, addr, vstream->port,
1107                                         vstream->port+1,
1108                                         used_pt, lc->rtp_conf.audio_jitt_comp, cam);
1109                                 video_stream_set_rtcp_information(call->videostream, cname,LINPHONE_RTCP_SDES_TOOL);
1110                         }
1111                 }else ms_warning("No video stream accepted.");
1112         }else{
1113                 ms_warning("No valid video stream defined.");
1114         }
1115 #endif
1116 }
1117
1118 void linphone_call_start_media_streams(LinphoneCall *call, bool_t all_inputs_muted, bool_t send_ringbacktone){
1119         LinphoneCore *lc=call->core;
1120         LinphoneAddress *me=linphone_core_get_primary_contact_parsed(lc);
1121         char *cname;
1122         bool_t use_arc;
1123 #ifdef VIDEO_ENABLED
1124         const SalStreamDescription *vstream=sal_media_description_find_stream(call->resultdesc,
1125                                                         SalProtoRtpAvp,SalVideo);
1126 #endif
1127         
1128         if(call->audiostream == NULL)
1129         {
1130                 ms_fatal("start_media_stream() called without prior init !");
1131                 return;
1132         }
1133         call->current_params = call->params;
1134         if (call->media_start_time==0) call->media_start_time=time(NULL);
1135         cname=linphone_address_as_string_uri_only(me);
1136
1137 #if defined(VIDEO_ENABLED)
1138         if (vstream && vstream->dir!=SalStreamInactive && vstream->payloads!=NULL){
1139                 /*when video is used, do not make adaptive rate control on audio, it is stupid.*/
1140                 use_arc=FALSE;
1141         }
1142 #endif
1143         linphone_call_start_audio_stream(call,cname,all_inputs_muted,send_ringbacktone,use_arc);
1144         linphone_call_start_video_stream(call,cname,all_inputs_muted);
1145
1146         call->all_muted=all_inputs_muted;
1147         call->playing_ringbacktone=send_ringbacktone;
1148         call->up_bw=linphone_core_get_upload_bandwidth(lc);
1149         
1150         if (ortp_zrtp_available()) {
1151                 OrtpZrtpParams params;
1152                 params.zid=get_hexa_zrtp_identifier(lc);
1153                 params.zid_file=lc->zrtp_secrets_cache;
1154                 audio_stream_enable_zrtp(call->audiostream,&params);
1155         }
1156
1157         goto end;
1158         end:
1159                 ms_free(cname);
1160                 linphone_address_destroy(me);
1161 }
1162
1163 static void linphone_call_log_fill_stats(LinphoneCallLog *log, AudioStream *st){
1164         audio_stream_get_local_rtp_stats (st,&log->local_stats);
1165         log->quality=audio_stream_get_average_quality_rating(st);
1166 }
1167
1168 void linphone_call_stop_media_streams(LinphoneCall *call){
1169         if (call->audiostream!=NULL) {
1170                 rtp_session_unregister_event_queue(call->audiostream->session,call->audiostream_app_evq);
1171                 ortp_ev_queue_flush(call->audiostream_app_evq);
1172                 ortp_ev_queue_destroy(call->audiostream_app_evq);
1173
1174                 if (call->audiostream->ec){
1175                         const char *state_str=NULL;
1176                         ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_GET_STATE_STRING,&state_str);
1177                         if (state_str){
1178                                 ms_message("Writing echo canceller state, %i bytes",strlen(state_str));
1179                                 lp_config_set_string(call->core->config,"sound","ec_state",state_str);
1180                         }
1181                 }
1182                 linphone_call_log_fill_stats (call->log,call->audiostream);
1183                 if (call->endpoint){
1184                         linphone_call_remove_from_conf(call);
1185                 }
1186                 audio_stream_stop(call->audiostream);
1187                 call->audiostream=NULL;
1188         }
1189
1190
1191 #ifdef VIDEO_ENABLED
1192         if (call->videostream!=NULL){
1193                 rtp_session_unregister_event_queue(call->videostream->session,call->videostream_app_evq);
1194                 ortp_ev_queue_flush(call->videostream_app_evq);
1195                 ortp_ev_queue_destroy(call->videostream_app_evq);
1196                 video_stream_stop(call->videostream);
1197                 call->videostream=NULL;
1198         }
1199         ms_event_queue_skip(call->core->msevq);
1200         
1201 #endif
1202         if (call->audio_profile){
1203                 rtp_profile_clear_all(call->audio_profile);
1204                 rtp_profile_destroy(call->audio_profile);
1205                 call->audio_profile=NULL;
1206         }
1207         if (call->video_profile){
1208                 rtp_profile_clear_all(call->video_profile);
1209                 rtp_profile_destroy(call->video_profile);
1210                 call->video_profile=NULL;
1211         }
1212 }
1213
1214
1215
1216 void linphone_call_enable_echo_cancellation(LinphoneCall *call, bool_t enable) {
1217         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
1218                 bool_t bypass_mode = !enable;
1219                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_SET_BYPASS_MODE,&bypass_mode);
1220         }
1221 }
1222 bool_t linphone_call_echo_cancellation_enabled(LinphoneCall *call) {
1223         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
1224                 bool_t val;
1225                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_GET_BYPASS_MODE,&val);
1226                 return !val;
1227         } else {
1228                 return linphone_core_echo_cancellation_enabled(call->core);
1229         }
1230 }
1231
1232 void linphone_call_enable_echo_limiter(LinphoneCall *call, bool_t val){
1233         if (call!=NULL && call->audiostream!=NULL ) {
1234                 if (val) {
1235                 const char *type=lp_config_get_string(call->core->config,"sound","el_type","mic");
1236                 if (strcasecmp(type,"mic")==0)
1237                         audio_stream_enable_echo_limiter(call->audiostream,ELControlMic);
1238                 else if (strcasecmp(type,"full")==0)
1239                         audio_stream_enable_echo_limiter(call->audiostream,ELControlFull);
1240                 } else {
1241                         audio_stream_enable_echo_limiter(call->audiostream,ELInactive);
1242                 }
1243         }
1244 }
1245
1246 bool_t linphone_call_echo_limiter_enabled(const LinphoneCall *call){
1247         if (call!=NULL && call->audiostream!=NULL ){
1248                 return call->audiostream->el_type !=ELInactive ;
1249         } else {
1250                 return linphone_core_echo_limiter_enabled(call->core);
1251         }
1252 }
1253
1254 /**
1255  * @addtogroup call_misc
1256  * @{
1257 **/ 
1258
1259 /**
1260  * Returns the measured sound volume played locally (received from remote)
1261  * It is expressed in dbm0. 
1262 **/
1263 float linphone_call_get_play_volume(LinphoneCall *call){
1264         AudioStream *st=call->audiostream;
1265         if (st && st->volsend){
1266                 float vol=0;
1267                 ms_filter_call_method(st->volsend,MS_VOLUME_GET,&vol);
1268                 return vol;
1269                 
1270         }
1271         return LINPHONE_VOLUME_DB_LOWEST;
1272 }
1273
1274 /**
1275  * Returns the measured sound volume recorded locally (sent to remote)
1276  * It is expressed in dbm0. 
1277 **/
1278 float linphone_call_get_record_volume(LinphoneCall *call){
1279         AudioStream *st=call->audiostream;
1280         if (st && st->volrecv){
1281                 float vol=0;
1282                 ms_filter_call_method(st->volrecv,MS_VOLUME_GET,&vol);
1283                 return vol;
1284                 
1285         }
1286         return LINPHONE_VOLUME_DB_LOWEST;
1287 }
1288
1289 /**
1290  * Obtain real-time quality rating of the call
1291  *
1292  * Based on local RTP statistics and RTCP feedback, a quality rating is computed and updated
1293  * during all the duration of the call. This function returns its value at the time of the function call.
1294  * It is expected that the rating is updated at least every 5 seconds or so.
1295  * The rating is a floating point number comprised between 0 and 5.
1296  *
1297  * 4-5 = good quality <br>
1298  * 3-4 = average quality <br>
1299  * 2-3 = poor quality <br>
1300  * 1-2 = very poor quality <br>
1301  * 0-1 = can't be worse, mostly unusable <br>
1302  *
1303  * @returns The function returns -1 if no quality measurement is available, for example if no 
1304  * active audio stream exist. Otherwise it returns the quality rating.
1305 **/
1306 float linphone_call_get_current_quality(LinphoneCall *call){
1307         if (call->audiostream){
1308                 return audio_stream_get_quality_rating(call->audiostream);
1309         }
1310         return -1;
1311 }
1312
1313 /**
1314  * Returns call quality averaged over all the duration of the call.
1315  *
1316  * See linphone_call_get_current_quality() for more details about quality measurement.
1317 **/
1318 float linphone_call_get_average_quality(LinphoneCall *call){
1319         if (call->audiostream){
1320                 return audio_stream_get_average_quality_rating(call->audiostream);
1321         }
1322         return -1;
1323 }
1324
1325 /**
1326  * @}
1327 **/
1328
1329 static void display_bandwidth(RtpSession *as, RtpSession *vs){
1330         ms_message("bandwidth usage: audio=[d=%.1f,u=%.1f] video=[d=%.1f,u=%.1f] kbit/sec",
1331         (as!=NULL) ? (rtp_session_compute_recv_bandwidth(as)*1e-3) : 0,
1332         (as!=NULL) ? (rtp_session_compute_send_bandwidth(as)*1e-3) : 0,
1333         (vs!=NULL) ? (rtp_session_compute_recv_bandwidth(vs)*1e-3) : 0,
1334         (vs!=NULL) ? (rtp_session_compute_send_bandwidth(vs)*1e-3) : 0);
1335 }
1336
1337 static void linphone_core_disconnected(LinphoneCore *lc, LinphoneCall *call){
1338         char temp[256];
1339         char *from=NULL;
1340         if(call)
1341                 from = linphone_call_get_remote_address_as_string(call);
1342         if (from)
1343         {
1344                 snprintf(temp,sizeof(temp),"Remote end %s seems to have disconnected, the call is going to be closed.",from);
1345                 free(from);
1346         }               
1347         else
1348         {
1349                 snprintf(temp,sizeof(temp),"Remote end seems to have disconnected, the call is going to be closed.");
1350         }
1351         if (lc->vtable.display_warning!=NULL)
1352                 lc->vtable.display_warning(lc,temp);
1353         linphone_core_terminate_call(lc,call);
1354 }
1355
1356 void linphone_call_background_tasks(LinphoneCall *call, bool_t one_second_elapsed){
1357         int disconnect_timeout = linphone_core_get_nortp_timeout(call->core);
1358         bool_t disconnected=FALSE;
1359         
1360         if (call->state==LinphoneCallStreamsRunning && one_second_elapsed){
1361                 RtpSession *as=NULL,*vs=NULL;
1362                 float audio_load=0, video_load=0;
1363                 if (call->audiostream!=NULL){
1364                         as=call->audiostream->session;
1365                         if (call->audiostream->ticker)
1366                                 audio_load=ms_ticker_get_average_load(call->audiostream->ticker);
1367                 }
1368                 if (call->videostream!=NULL){
1369                         if (call->videostream->ticker)
1370                                 video_load=ms_ticker_get_average_load(call->videostream->ticker);
1371                         vs=call->videostream->session;
1372                 }
1373                 display_bandwidth(as,vs);
1374                 ms_message("Thread processing load: audio=%f\tvideo=%f",audio_load,video_load);
1375         }
1376 #ifdef VIDEO_ENABLED
1377         if (call->videostream!=NULL) {
1378                 // Beware that the application queue should not depend on treatments fron the
1379                 // mediastreamer queue.
1380                 video_stream_iterate(call->videostream);
1381
1382                 if (call->videostream_app_evq){
1383                         OrtpEvent *ev;
1384                         while (NULL != (ev=ortp_ev_queue_get(call->videostream_app_evq))){
1385                                 OrtpEventType evt=ortp_event_get_type(ev);
1386                                 if (evt == ORTP_EVENT_ZRTP_ENCRYPTION_CHANGED){
1387                                         OrtpEventData *evd=ortp_event_get_data(ev);
1388                                         linphone_call_videostream_encryption_changed(call, evd->info.zrtp_stream_encrypted);
1389                                 }
1390                                 ortp_event_destroy(ev);
1391                         }
1392                 }
1393         }
1394 #endif
1395         if (call->audiostream!=NULL) {
1396                 // Beware that the application queue should not depend on treatments fron the
1397                 // mediastreamer queue.
1398                 audio_stream_iterate(call->audiostream);
1399
1400                 if (call->audiostream->evq){
1401                         OrtpEvent *ev;
1402                         while (NULL != (ev=ortp_ev_queue_get(call->audiostream_app_evq))){
1403                                 OrtpEventType evt=ortp_event_get_type(ev);
1404                                 if (evt == ORTP_EVENT_ZRTP_ENCRYPTION_CHANGED){
1405                                         OrtpEventData *evd=ortp_event_get_data(ev);
1406                                         linphone_call_audiostream_encryption_changed(call, evd->info.zrtp_stream_encrypted);
1407                                 } else if (evt == ORTP_EVENT_ZRTP_SAS_READY) {
1408                                         OrtpEventData *evd=ortp_event_get_data(ev);
1409                                         linphone_call_audiostream_auth_token_ready(call, evd->info.zrtp_sas.sas, evd->info.zrtp_sas.verified);
1410                                 }
1411                                 ortp_event_destroy(ev);
1412                         }
1413                 }
1414         }
1415         if (call->state==LinphoneCallStreamsRunning && one_second_elapsed && call->audiostream!=NULL && disconnect_timeout>0 )
1416                 disconnected=!audio_stream_alive(call->audiostream,disconnect_timeout);
1417         if (disconnected)
1418                 linphone_core_disconnected(call->core,call);
1419 }
1420
1421 void linphone_call_log_completed(LinphoneCall *call){
1422         LinphoneCore *lc=call->core;
1423         
1424         call->log->duration=time(NULL)-call->start_time;
1425         
1426         if (call->log->status==LinphoneCallMissed){
1427                 char *info;
1428                 lc->missed_calls++;
1429                 info=ortp_strdup_printf(ngettext("You have missed %i call.",
1430                                          "You have missed %i calls.", lc->missed_calls),
1431                                 lc->missed_calls);
1432         if (lc->vtable.display_status!=NULL)
1433             lc->vtable.display_status(lc,info);
1434                 ms_free(info);
1435         }
1436         lc->call_logs=ms_list_prepend(lc->call_logs,(void *)call->log);
1437         if (ms_list_size(lc->call_logs)>lc->max_call_logs){
1438                 MSList *elem,*prevelem=NULL;
1439                 /*find the last element*/
1440                 for(elem=lc->call_logs;elem!=NULL;elem=elem->next){
1441                         prevelem=elem;
1442                 }
1443                 elem=prevelem;
1444                 linphone_call_log_destroy((LinphoneCallLog*)elem->data);
1445                 lc->call_logs=ms_list_remove_link(lc->call_logs,elem);
1446         }
1447         if (lc->vtable.call_log_updated!=NULL){
1448                 lc->vtable.call_log_updated(lc,call->log);
1449         }
1450         call_logs_write_to_config_file(lc);
1451 }
1452
1453