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