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