]> sjero.net Git - linphone/blob - coreapi/linphonecall.c
Merge branch 'master' of git.savannah.nongnu.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
29
30 #include "mediastreamer2/mediastream.h"
31 #include "mediastreamer2/msvolume.h"
32 #include "mediastreamer2/msequalizer.h"
33 #include "mediastreamer2/msfileplayer.h"
34 #include "mediastreamer2/msjpegwriter.h"
35
36 #ifdef VIDEO_ENABLED
37 static MSWebCam *get_nowebcam_device(){
38         return ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),"StaticImage: Static picture");
39 }
40 #endif
41
42
43 static MSList *make_codec_list(LinphoneCore *lc, const MSList *codecs, int bandwidth_limit){
44         MSList *l=NULL;
45         const MSList *it;
46         for(it=codecs;it!=NULL;it=it->next){
47                 PayloadType *pt=(PayloadType*)it->data;
48                 if (pt->flags & PAYLOAD_TYPE_ENABLED){
49                         if (bandwidth_limit>0 && !linphone_core_is_payload_type_usable_for_bandwidth(lc,pt,bandwidth_limit)){
50                                 ms_message("Codec %s/%i eliminated because of audio bandwidth constraint.",pt->mime_type,pt->clock_rate);
51                                 continue;
52                         }
53                         if (linphone_core_check_payload_type_usability(lc,pt)){
54                                 l=ms_list_append(l,payload_type_clone(pt));
55                         }
56                 }
57         }
58         return l;
59 }
60
61 SalMediaDescription *create_local_media_description(LinphoneCore *lc, LinphoneCall *call){
62         MSList *l;
63         PayloadType *pt;
64         const char *me=linphone_core_get_identity(lc);
65         LinphoneAddress *addr=linphone_address_new(me);
66         const char *username=linphone_address_get_username (addr);
67         SalMediaDescription *md=sal_media_description_new();
68         
69         md->nstreams=1;
70         strncpy(md->addr,call->localip,sizeof(md->addr));
71         strncpy(md->username,username,sizeof(md->username));
72         md->bandwidth=linphone_core_get_download_bandwidth(lc);
73         
74         /*set audio capabilities */
75         strncpy(md->streams[0].addr,call->localip,sizeof(md->streams[0].addr));
76         md->streams[0].port=call->audio_port;
77         md->streams[0].proto=SalProtoRtpAvp;
78         md->streams[0].type=SalAudio;
79         md->streams[0].ptime=lc->net_conf.down_ptime;
80         l=make_codec_list(lc,lc->codecs_conf.audio_codecs,call->params.audio_bw);
81         pt=payload_type_clone(rtp_profile_get_payload_from_mime(&av_profile,"telephone-event"));
82         l=ms_list_append(l,pt);
83         md->streams[0].payloads=l;
84         
85
86         if (call->params.has_video){
87                 md->nstreams++;
88                 md->streams[1].port=call->video_port;
89                 md->streams[1].proto=SalProtoRtpAvp;
90                 md->streams[1].type=SalVideo;
91                 l=make_codec_list(lc,lc->codecs_conf.video_codecs,0);
92                 md->streams[1].payloads=l;
93         }
94         linphone_address_destroy(addr);
95         return md;
96 }
97
98 static int find_port_offset(LinphoneCore *lc){
99         int offset;
100         MSList *elem;
101         int audio_port;
102         bool_t already_used=FALSE;
103         for(offset=0;offset<100;offset+=2){
104                 audio_port=linphone_core_get_audio_port (lc)+offset;
105                 already_used=FALSE;
106                 for(elem=lc->calls;elem!=NULL;elem=elem->next){
107                         LinphoneCall *call=(LinphoneCall*)elem->data;
108                         if (call->audio_port==audio_port) {
109                                 already_used=TRUE;
110                                 break;
111                         }
112                 }
113                 if (!already_used) break;
114         }
115         if (offset==100){
116                 ms_error("Could not find any free port !");
117                 return -1;
118         }
119         return offset;
120 }
121
122 static void linphone_call_init_common(LinphoneCall *call, LinphoneAddress *from, LinphoneAddress *to){
123         int port_offset;
124         call->refcnt=1;
125         call->state=LinphoneCallIdle;
126         call->start_time=time(NULL);
127         call->media_start_time=0;
128         call->log=linphone_call_log_new(call, from, to);
129         linphone_core_notify_all_friends(call->core,LinphoneStatusOnThePhone);
130         port_offset=find_port_offset (call->core);
131         if (port_offset==-1) return;
132         call->audio_port=linphone_core_get_audio_port(call->core)+port_offset;
133         call->video_port=linphone_core_get_video_port(call->core)+port_offset;
134         
135 }
136
137 static void discover_mtu(LinphoneCore *lc, const char *remote){
138         int mtu;
139         if (lc->net_conf.mtu==0 ){
140                 /*attempt to discover mtu*/
141                 mtu=ms_discover_mtu(remote);
142                 if (mtu>0){
143                         ms_set_mtu(mtu);
144                         ms_message("Discovered mtu is %i, RTP payload max size is %i",
145                                 mtu, ms_get_payload_max_size());
146                 }
147         }
148 }
149
150 LinphoneCall * linphone_call_new_outgoing(struct _LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, const LinphoneCallParams *params)
151 {
152         LinphoneCall *call=ms_new0(LinphoneCall,1);
153         call->dir=LinphoneCallOutgoing;
154         call->op=sal_op_new(lc->sal);
155         sal_op_set_user_pointer(call->op,call);
156         call->core=lc;
157         linphone_core_get_local_ip(lc,linphone_address_get_domain(to),call->localip);
158         linphone_call_init_common(call,from,to);
159         call->params=*params;
160         call->localdesc=create_local_media_description (lc,call);
161         call->camera_active=params->has_video;
162         if (linphone_core_get_firewall_policy(call->core)==LinphonePolicyUseStun)
163                 linphone_core_run_stun_tests(call->core,call);
164         discover_mtu(lc,linphone_address_get_domain (to));
165         if (params->referer){
166                 sal_call_set_referer (call->op,params->referer->op);
167         }
168         return call;
169 }
170
171 LinphoneCall * linphone_call_new_incoming(LinphoneCore *lc, LinphoneAddress *from, LinphoneAddress *to, SalOp *op){
172         LinphoneCall *call=ms_new0(LinphoneCall,1);
173         char *to_str;
174         char *from_str;
175
176         call->dir=LinphoneCallIncoming;
177         sal_op_set_user_pointer(op,call);
178         call->op=op;
179         call->core=lc;
180
181         if (lc->sip_conf.ping_with_options){
182                 /*the following sends an option request back to the caller so that
183                  we get a chance to discover our nat'd address before answering.*/
184                 call->ping_op=sal_op_new(lc->sal);
185                 to_str=linphone_address_as_string(to);
186                 from_str=linphone_address_as_string(from);
187                 sal_op_set_route(call->ping_op,sal_op_get_network_origin(call->op));
188                 sal_op_set_user_pointer(call->ping_op,call);
189                 sal_ping(call->ping_op,to_str,from_str);
190                 ms_free(to_str);
191                 ms_free(from_str);
192         }
193         
194         linphone_address_clean(from);
195         linphone_core_get_local_ip(lc,linphone_address_get_domain(from),call->localip);
196         linphone_call_init_common(call, from, to);
197         call->params.has_video=linphone_core_video_enabled(lc);
198         call->localdesc=create_local_media_description (lc,call);
199         call->camera_active=call->params.has_video;
200         if (linphone_core_get_firewall_policy(call->core)==LinphonePolicyUseStun)
201                 linphone_core_run_stun_tests(call->core,call);
202         discover_mtu(lc,linphone_address_get_domain(from));
203         return call;
204 }
205
206 /* this function is called internally to get rid of a call.
207  It performs the following tasks:
208  - remove the call from the internal list of calls
209  - unref the LinphoneCall object
210  - update the call logs accordingly
211 */
212
213 static void linphone_call_set_terminated(LinphoneCall *call){
214         LinphoneCallStatus status=LinphoneCallAborted;
215         LinphoneCore *lc=call->core;
216         
217         linphone_core_update_allocated_audio_bandwidth(lc);
218         if (call->state==LinphoneCallEnd){
219                 if (call->reason==LinphoneReasonDeclined){
220                         status=LinphoneCallDeclined;
221                 }
222                 else status=LinphoneCallSuccess;
223                 
224         }
225         linphone_call_log_completed(call->log,call, status);
226         
227         if (call == lc->current_call){
228                 ms_message("Resetting the current call");
229                 lc->current_call=NULL;
230         }
231
232         if (linphone_core_del_call(lc,call) != 0){
233                 ms_error("Could not remove the call from the list !!!");
234         }
235         
236         if (ms_list_size(lc->calls)==0)
237                 linphone_core_notify_all_friends(lc,lc->presence_mode);
238         
239         if (call->op!=NULL) {
240                 /* so that we cannot have anymore upcalls for SAL
241                  concerning this call*/
242                 sal_op_release(call->op);
243                 call->op=NULL;
244         }
245         linphone_call_unref(call);
246 }
247
248 const char *linphone_call_state_to_string(LinphoneCallState cs){
249         switch (cs){
250                 case LinphoneCallIdle:
251                         return "LinphoneCallIdle";
252                 case LinphoneCallIncomingReceived:
253                         return "LinphoneCallIncomingReceived";
254                 case LinphoneCallOutgoingInit:
255                         return "LinphoneCallOutgoingInit";
256                 case LinphoneCallOutgoingProgress:
257                         return "LinphoneCallOutgoingProgress";
258                 case LinphoneCallOutgoingRinging:
259                         return "LinphoneCallOutgoingRinging";
260                 case LinphoneCallOutgoingEarlyMedia:
261                         return "LinphoneCallOutgoingEarlyMedia";
262                 case LinphoneCallConnected:
263                         return "LinphoneCallConnected";
264                 case LinphoneCallStreamsRunning:
265                         return "LinphoneCallStreamsRunning";
266                 case LinphoneCallPausing:
267                         return "LinphoneCallPausing";
268                 case LinphoneCallPaused:
269                         return "LinphoneCallPaused";
270                 case LinphoneCallResuming:
271                         return "LinphoneCallResuming";
272                 case LinphoneCallRefered:
273                         return "LinphoneCallRefered";
274                 case LinphoneCallError:
275                         return "LinphoneCallError";
276                 case LinphoneCallEnd:
277                         return "LinphoneCallEnd";
278                 case LinphoneCallPausedByRemote:
279                         return "LinphoneCallPausedByRemote";
280                 case LinphoneCallUpdatedByRemote:
281                         return "LinphoneCallUpdatedByRemote";
282                 case LinphoneCallIncomingEarlyMedia:
283                         return "LinphoneCallIncomingEarlyMedia";
284                 case LinphoneCallUpdated:
285                         return "LinphoneCallUpdated";
286         }
287         return "undefined state";
288 }
289
290 void linphone_call_set_state(LinphoneCall *call, LinphoneCallState cstate, const char *message){
291         LinphoneCore *lc=call->core;
292         bool_t finalize_call=FALSE;
293         if (call->state!=cstate){
294                 ms_message("Call %p: moving from state %s to %s",call,linphone_call_state_to_string(call->state),
295                            linphone_call_state_to_string(cstate));
296                 if (cstate!=LinphoneCallRefered){
297                         /*LinphoneCallRefered is rather an event, not a state.
298                          Indeed it does not change the state of the call (still paused or running)*/
299                         call->state=cstate;
300                 }
301                 if (cstate==LinphoneCallEnd || cstate==LinphoneCallError){
302                         finalize_call=TRUE;
303                         linphone_call_ref(call);
304                         linphone_call_set_terminated (call);
305                 }
306                 if (lc->vtable.call_state_changed)
307                         lc->vtable.call_state_changed(lc,call,cstate,message);
308                 if (finalize_call)
309                         linphone_call_unref(call);
310         }
311 }
312
313 static void linphone_call_destroy(LinphoneCall *obj)
314 {
315         if (obj->op!=NULL) {
316                 sal_op_release(obj->op);
317                 obj->op=NULL;
318         }
319         if (obj->resultdesc!=NULL) {
320                 sal_media_description_unref(obj->resultdesc);
321                 obj->resultdesc=NULL;
322         }
323         if (obj->localdesc!=NULL) {
324                 sal_media_description_unref(obj->localdesc);
325                 obj->localdesc=NULL;
326         }
327         if (obj->ping_op) {
328                 sal_op_release(obj->ping_op);
329         }
330         if (obj->refer_to){
331                 ms_free(obj->refer_to);
332         }
333         ms_free(obj);
334 }
335
336 /**
337  * @addtogroup call_control
338  * @{
339 **/
340
341 /**
342  * Increments the call 's reference count.
343  * An application that wishes to retain a pointer to call object
344  * must use this function to unsure the pointer remains
345  * valid. Once the application no more needs this pointer,
346  * it must call linphone_call_unref().
347 **/
348 void linphone_call_ref(LinphoneCall *obj){
349         obj->refcnt++;
350 }
351
352 /**
353  * Decrements the call object reference count.
354  * See linphone_call_ref().
355 **/
356 void linphone_call_unref(LinphoneCall *obj){
357         obj->refcnt--;
358         if (obj->refcnt==0){
359                 linphone_call_destroy(obj);
360         }
361 }
362
363 /**
364  * Returns current parameters associated to the call.
365 **/
366 const LinphoneCallParams * linphone_call_get_current_params(const LinphoneCall *call){
367         return &call->current_params;
368 }
369
370 /**
371  * Returns the remote address associated to this call
372  *
373 **/
374 const LinphoneAddress * linphone_call_get_remote_address(const LinphoneCall *call){
375         return call->dir==LinphoneCallIncoming ? call->log->from : call->log->to;
376 }
377
378 /**
379  * Returns the remote address associated to this call as a string.
380  *
381  * The result string must be freed by user using ms_free().
382 **/
383 char *linphone_call_get_remote_address_as_string(const LinphoneCall *call){
384         return linphone_address_as_string(linphone_call_get_remote_address(call));
385 }
386
387 /**
388  * Retrieves the call's current state.
389 **/
390 LinphoneCallState linphone_call_get_state(const LinphoneCall *call){
391         return call->state;
392 }
393
394 /**
395  * Returns the reason for a call termination (either error or normal termination)
396 **/
397 LinphoneReason linphone_call_get_reason(const LinphoneCall *call){
398         return call->reason;
399 }
400
401 /**
402  * Get the user_pointer in the LinphoneCall
403  *
404  * @ingroup call_control
405  *
406  * return user_pointer an opaque user pointer that can be retrieved at any time
407 **/
408 void *linphone_call_get_user_pointer(LinphoneCall *call)
409 {
410         return call->user_pointer;
411 }
412
413 /**
414  * Set the user_pointer in the LinphoneCall
415  *
416  * @ingroup call_control
417  *
418  * the user_pointer is an opaque user pointer that can be retrieved at any time in the LinphoneCall
419 **/
420 void linphone_call_set_user_pointer(LinphoneCall *call, void *user_pointer)
421 {
422         call->user_pointer = user_pointer;
423 }
424
425 /**
426  * Returns the call log associated to this call.
427 **/
428 LinphoneCallLog *linphone_call_get_call_log(const LinphoneCall *call){
429         return call->log;
430 }
431
432 /**
433  * Returns the refer-to uri (if the call was transfered).
434 **/
435 const char *linphone_call_get_refer_to(const LinphoneCall *call){
436         return call->refer_to;
437 }
438
439 /**
440  * Returns direction of the call (incoming or outgoing).
441 **/
442 LinphoneCallDir linphone_call_get_dir(const LinphoneCall *call){
443         return call->log->dir;
444 }
445
446 /**
447  * Returns the far end's user agent description string, if available.
448 **/
449 const char *linphone_call_get_remote_user_agent(LinphoneCall *call){
450         if (call->op){
451                 return sal_op_get_remote_ua (call->op);
452         }
453         return NULL;
454 }
455
456 /**
457  * Returns true if this calls has received a transfer that has not been
458  * executed yet.
459  * Pending transfers are executed when this call is being paused or closed,
460  * locally or by remote endpoint.
461  * If the call is already paused while receiving the transfer request, the 
462  * transfer immediately occurs.
463 **/
464 bool_t linphone_call_has_transfer_pending(const LinphoneCall *call){
465         return call->refer_pending;
466 }
467
468 /**
469  * Returns call's duration in seconds.
470 **/
471 int linphone_call_get_duration(const LinphoneCall *call){
472         if (call->media_start_time==0) return 0;
473         return time(NULL)-call->media_start_time;
474 }
475
476 /**
477  * Indicate whether camera input should be sent to remote end.
478 **/
479 void linphone_call_enable_camera (LinphoneCall *call, bool_t enable){
480 #ifdef VIDEO_ENABLED
481         if (call->videostream!=NULL && call->videostream->ticker!=NULL){
482                 LinphoneCore *lc=call->core;
483                 MSWebCam *nowebcam=get_nowebcam_device();
484                 if (call->camera_active!=enable && lc->video_conf.device!=nowebcam){
485                         video_stream_change_camera(call->videostream,
486                                      enable ? lc->video_conf.device : nowebcam);
487                 }
488         }
489         call->camera_active=enable;
490 #endif
491 }
492
493 /**
494  * Take a photo of currently received video and write it into a jpeg file.
495 **/
496 int linphone_call_take_video_snapshot(LinphoneCall *call, const char *file){
497 #ifdef VIDEO_ENABLED
498         if (call->videostream!=NULL && call->videostream->jpegwriter!=NULL){
499                 return ms_filter_call_method(call->videostream->jpegwriter,MS_JPEG_WRITER_TAKE_SNAPSHOT,(void*)file);
500         }
501         ms_warning("Cannot take snapshot: no currently running video stream on this call.");
502         return -1;
503 #endif
504         return -1;
505 }
506
507 /**
508  *
509 **/
510 bool_t linphone_call_camera_enabled (const LinphoneCall *call){
511         return call->camera_active;
512 }
513
514 /**
515  * 
516 **/
517 void linphone_call_params_enable_video(LinphoneCallParams *cp, bool_t enabled){
518         cp->has_video=enabled;
519 }
520
521 /**
522  *
523 **/
524 bool_t linphone_call_params_video_enabled(const LinphoneCallParams *cp){
525         return cp->has_video;
526 }
527
528 /**
529  * Enable sending of real early media (during outgoing calls).
530 **/
531 void linphone_call_params_enable_early_media_sending(LinphoneCallParams *cp, bool_t enabled){
532         cp->real_early_media=enabled;
533 }
534
535 bool_t linphone_call_params_early_media_sending_enabled(const LinphoneCallParams *cp){
536         return cp->real_early_media;
537 }
538
539 /**
540  * Refine bandwidth settings for this call by setting a bandwidth limit for audio streams.
541  * As a consequence, codecs whose bitrates are not compatible with this limit won't be used.
542 **/
543 void linphone_call_params_set_audio_bandwidth_limit(LinphoneCallParams *cp, int bandwidth){
544         cp->audio_bw=bandwidth;
545 }
546
547 /**
548  *
549 **/
550 LinphoneCallParams * linphone_call_params_copy(const LinphoneCallParams *cp){
551         LinphoneCallParams *ncp=ms_new0(LinphoneCallParams,1);
552         memcpy(ncp,cp,sizeof(LinphoneCallParams));
553         return ncp;
554 }
555
556 /**
557  *
558 **/
559 void linphone_call_params_destroy(LinphoneCallParams *p){
560         ms_free(p);
561 }
562
563 /**
564  * @}
565 **/
566
567
568 #ifdef TEST_EXT_RENDERER
569 static void rendercb(void *data, const MSPicture *local, const MSPicture *remote){
570         ms_message("rendercb, local buffer=%p, remote buffer=%p",
571                    local ? local->planes[0] : NULL, remote? remote->planes[0] : NULL);
572 }
573 #endif
574
575 #ifdef VIDEO_ENABLED
576 static void video_stream_event_cb(void *user_pointer, const MSFilter *f, const unsigned int event_id, const void *args){
577         ms_warning("In linphonecall.c: video_stream_event_cb");
578         switch (event_id) {
579                 case MS_VIDEO_DECODER_DECODING_ERRORS:
580                         ms_warning("CAse is MS_VIDEO_DECODER_DECODING_ERRORS");
581                         linphone_call_send_vfu_request((LinphoneCall*) user_pointer);
582                         break;
583                 default:
584                         ms_warning("Unhandled event %i", event_id);
585                         break;
586         }
587 }
588 #endif
589
590 void linphone_call_init_media_streams(LinphoneCall *call){
591         LinphoneCore *lc=call->core;
592         SalMediaDescription *md=call->localdesc;
593         AudioStream *audiostream;
594         
595         call->audiostream=audiostream=audio_stream_new(md->streams[0].port,linphone_core_ipv6_enabled(lc));
596         if (linphone_core_echo_limiter_enabled(lc)){
597                 const char *type=lp_config_get_string(lc->config,"sound","el_type","mic");
598                 if (strcasecmp(type,"mic")==0)
599                         audio_stream_enable_echo_limiter(audiostream,ELControlMic);
600                 else if (strcasecmp(type,"full")==0)
601                         audio_stream_enable_echo_limiter(audiostream,ELControlFull);
602         }
603         audio_stream_enable_gain_control(audiostream,TRUE);
604         if (linphone_core_echo_cancellation_enabled(lc)){
605                 int len,delay,framesize;
606                 len=lp_config_get_int(lc->config,"sound","ec_tail_len",0);
607                 delay=lp_config_get_int(lc->config,"sound","ec_delay",0);
608                 framesize=lp_config_get_int(lc->config,"sound","ec_framesize",0);
609                 audio_stream_set_echo_canceller_params(audiostream,len,delay,framesize);
610         }
611         audio_stream_enable_automatic_gain_control(audiostream,linphone_core_agc_enabled(lc));
612         {
613                 int enabled=lp_config_get_int(lc->config,"sound","noisegate",0);
614                 audio_stream_enable_noise_gate(audiostream,enabled);
615         }
616         if (lc->a_rtp)
617                 rtp_session_set_transports(audiostream->session,lc->a_rtp,lc->a_rtcp);
618
619 #ifdef VIDEO_ENABLED
620         if ((lc->video_conf.display || lc->video_conf.capture) && md->streams[1].port>0){
621                 call->videostream=video_stream_new(md->streams[1].port,linphone_core_ipv6_enabled(lc));
622         if( lc->video_conf.displaytype != NULL)
623                 video_stream_set_display_filter_name(call->videostream,lc->video_conf.displaytype);
624         video_stream_set_event_callback(call->videostream,video_stream_event_cb, call);
625 #ifdef TEST_EXT_RENDERER
626                 video_stream_set_render_callback(call->videostream,rendercb,NULL);
627 #endif
628         }
629 #else
630         call->videostream=NULL;
631 #endif
632 }
633
634
635 static int dtmf_tab[16]={'0','1','2','3','4','5','6','7','8','9','*','#','A','B','C','D'};
636
637 static void linphone_core_dtmf_received(RtpSession* s, int dtmf, void* user_data){
638         LinphoneCore* lc = (LinphoneCore*)user_data;
639         if (dtmf<0 || dtmf>15){
640                 ms_warning("Bad dtmf value %i",dtmf);
641                 return;
642         }
643         if (lc->vtable.dtmf_received != NULL)
644                 lc->vtable.dtmf_received(lc, linphone_core_get_current_call(lc), dtmf_tab[dtmf]);
645 }
646
647 static void parametrize_equalizer(LinphoneCore *lc, AudioStream *st){
648         if (st->equalizer){
649                 MSFilter *f=st->equalizer;
650                 int enabled=lp_config_get_int(lc->config,"sound","eq_active",0);
651                 const char *gains=lp_config_get_string(lc->config,"sound","eq_gains",NULL);
652                 ms_filter_call_method(f,MS_EQUALIZER_SET_ACTIVE,&enabled);
653                 if (enabled){
654                         if (gains){
655                                 do{
656                                         int bytes;
657                                         MSEqualizerGain g;
658                                         if (sscanf(gains,"%f:%f:%f %n",&g.frequency,&g.gain,&g.width,&bytes)==3){
659                                                 ms_message("Read equalizer gains: %f(~%f) --> %f",g.frequency,g.width,g.gain);
660                                                 ms_filter_call_method(f,MS_EQUALIZER_SET_GAIN,&g);
661                                                 gains+=bytes;
662                                         }else break;
663                                 }while(1);
664                         }
665                 }
666         }
667 }
668
669
670 static void post_configure_audio_streams(LinphoneCall*call){
671         AudioStream *st=call->audiostream;
672         LinphoneCore *lc=call->core;
673         float mic_gain=lp_config_get_float(lc->config,"sound","mic_gain",1);
674         float thres = 0;
675         float recv_gain;
676         float ng_thres=lp_config_get_float(lc->config,"sound","ng_thres",0.05);
677         float ng_floorgain=lp_config_get_float(lc->config,"sound","ng_floorgain",0);
678         int dc_removal=lp_config_get_int(lc->config,"sound","dc_removal",0);
679         
680         if (!call->audio_muted)
681                 audio_stream_set_mic_gain(st,mic_gain);
682         else 
683                 audio_stream_set_mic_gain(st,0);
684
685         recv_gain = lc->sound_conf.soft_play_lev;
686         if (recv_gain != 0) {
687                 linphone_core_set_playback_gain_db (lc,recv_gain);
688         }
689         if (st->volsend){
690                 ms_filter_call_method(st->volsend,MS_VOLUME_REMOVE_DC,&dc_removal);
691                 float speed=lp_config_get_float(lc->config,"sound","el_speed",-1);
692                 thres=lp_config_get_float(lc->config,"sound","el_thres",-1);
693                 float force=lp_config_get_float(lc->config,"sound","el_force",-1);
694                 int sustain=lp_config_get_int(lc->config,"sound","el_sustain",-1);
695                 float transmit_thres=lp_config_get_float(lc->config,"sound","el_transmit_thres",-1);
696                 MSFilter *f=NULL;
697                 f=st->volsend;
698                 if (speed==-1) speed=0.03;
699                 if (force==-1) force=25;
700                 ms_filter_call_method(f,MS_VOLUME_SET_EA_SPEED,&speed);
701                 ms_filter_call_method(f,MS_VOLUME_SET_EA_FORCE,&force);
702                 if (thres!=-1)
703                         ms_filter_call_method(f,MS_VOLUME_SET_EA_THRESHOLD,&thres);
704                 if (sustain!=-1)
705                         ms_filter_call_method(f,MS_VOLUME_SET_EA_SUSTAIN,&sustain);
706                 if (transmit_thres!=-1)
707                                 ms_filter_call_method(f,MS_VOLUME_SET_EA_TRANSMIT_THRESHOLD,&transmit_thres);
708
709                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&ng_thres);
710                 ms_filter_call_method(st->volsend,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&ng_floorgain);
711         }
712         if (st->volrecv){
713                 /* parameters for a limited noise-gate effect, using echo limiter threshold */
714                 float floorgain = 1/mic_gain;
715                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_THRESHOLD,&thres);
716                 ms_filter_call_method(st->volrecv,MS_VOLUME_SET_NOISE_GATE_FLOORGAIN,&floorgain);
717         }
718         parametrize_equalizer(lc,st);
719         if (lc->vtable.dtmf_received!=NULL){
720                 /* replace by our default action*/
721                 audio_stream_play_received_dtmfs(call->audiostream,FALSE);
722                 rtp_session_signal_connect(call->audiostream->session,"telephone-event",(RtpCallback)linphone_core_dtmf_received,(unsigned long)lc);
723         }
724 }
725
726
727
728
729 static RtpProfile *make_profile(LinphoneCall *call, const SalMediaDescription *md, const SalStreamDescription *desc, int *used_pt){
730         int bw;
731         const MSList *elem;
732         RtpProfile *prof=rtp_profile_new("Call profile");
733         bool_t first=TRUE;
734         int remote_bw=0;
735         LinphoneCore *lc=call->core;
736         *used_pt=-1;
737         
738         for(elem=desc->payloads;elem!=NULL;elem=elem->next){
739                 PayloadType *pt=(PayloadType*)elem->data;
740                 int number;
741                 
742                 if (first) {
743                         if (desc->type==SalAudio){
744                                 linphone_core_update_allocated_audio_bandwidth_in_call(call,pt);
745                         }
746                         *used_pt=payload_type_get_number(pt);
747                         first=FALSE;
748                 }
749                 if (desc->bandwidth>0) remote_bw=desc->bandwidth;
750                 else if (md->bandwidth>0) {
751                         /*case where b=AS is given globally, not per stream*/
752                         remote_bw=md->bandwidth;
753                         if (desc->type==SalVideo){
754                                 remote_bw=get_video_bandwidth(remote_bw,call->audio_bw);
755                         }
756                 }
757                 
758                 if (desc->type==SalAudio){                      
759                                 bw=get_min_bandwidth(call->audio_bw,remote_bw);
760                 }else bw=get_min_bandwidth(get_video_bandwidth(linphone_core_get_upload_bandwidth (lc),call->audio_bw),remote_bw);
761                 if (bw>0) pt->normal_bitrate=bw*1000;
762                 else if (desc->type==SalAudio){
763                         pt->normal_bitrate=-1;
764                 }
765                 if (desc->ptime>0){
766                         char tmp[40];
767                         snprintf(tmp,sizeof(tmp),"ptime=%i",desc->ptime);
768                         payload_type_append_send_fmtp(pt,tmp);
769                 }
770                 number=payload_type_get_number(pt);
771                 if (rtp_profile_get_payload(prof,number)!=NULL){
772                         ms_warning("A payload type with number %i already exists in profile !",number);
773                 }else
774                         rtp_profile_set_payload(prof,number,pt);
775         }
776         return prof;
777 }
778
779
780 static void setup_ring_player(LinphoneCore *lc, LinphoneCall *call){
781         int pause_time=3000;
782         audio_stream_play(call->audiostream,lc->sound_conf.ringback_tone);
783         ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
784 }
785
786
787 void linphone_call_start_media_streams(LinphoneCall *call, bool_t all_inputs_muted, bool_t send_ringbacktone){
788         LinphoneCore *lc=call->core;
789         LinphoneAddress *me=linphone_core_get_primary_contact_parsed(lc);
790         const char *tool="linphone-" LINPHONE_VERSION;
791         char *cname;
792         int used_pt=-1;
793 #ifdef VIDEO_ENABLED
794         const SalStreamDescription *vstream=sal_media_description_find_stream(call->resultdesc,
795                                                         SalProtoRtpAvp,SalVideo);
796 #endif
797         
798         if(call->audiostream == NULL)
799         {
800                 ms_fatal("start_media_stream() called without prior init !");
801                 return;
802         }
803         call->current_params = call->params;
804         /* adjust rtp jitter compensation. It must be at least the latency of the sound card */
805         int jitt_comp=MAX(lc->sound_conf.latency,lc->rtp_conf.audio_jitt_comp);
806
807         if (call->media_start_time==0) call->media_start_time=time(NULL);
808
809         cname=linphone_address_as_string_uri_only(me);
810         {
811                 const SalStreamDescription *stream=sal_media_description_find_stream(call->resultdesc,
812                                                         SalProtoRtpAvp,SalAudio);
813                 if (stream && stream->dir!=SalStreamInactive){
814                         MSSndCard *playcard=lc->sound_conf.lsd_card ? 
815                                 lc->sound_conf.lsd_card : lc->sound_conf.play_sndcard;
816                         MSSndCard *captcard=lc->sound_conf.capt_sndcard;
817                         const char *playfile=lc->play_file;
818                         const char *recfile=lc->rec_file;
819                         call->audio_profile=make_profile(call,call->resultdesc,stream,&used_pt);
820                         bool_t use_ec;
821
822                         if (used_pt!=-1){
823                                 if (playcard==NULL) {
824                                         ms_warning("No card defined for playback !");
825                                 }
826                                 if (captcard==NULL) {
827                                         ms_warning("No card defined for capture !");
828                                 }
829                                 /*Replace soundcard filters by inactive file players or recorders
830                                  when placed in recvonly or sendonly mode*/
831                                 if (stream->port==0 || stream->dir==SalStreamRecvOnly){
832                                         captcard=NULL;
833                                         playfile=NULL;
834                                 }else if (stream->dir==SalStreamSendOnly){
835                                         playcard=NULL;
836                                         captcard=NULL;
837                                         recfile=NULL;
838                                         /*And we will eventually play "playfile" if set by the user*/
839                                         /*playfile=NULL;*/
840                                 }
841                                 if (send_ringbacktone){
842                                         captcard=NULL;
843                                         playfile=NULL;/* it is setup later*/
844                                 }
845                                 /*if playfile are supplied don't use soundcards*/
846                                 if (lc->use_files) {
847                                         captcard=NULL;
848                                         playcard=NULL;
849                                 }
850                                 use_ec=captcard==NULL ? FALSE : linphone_core_echo_cancellation_enabled(lc);
851 #if defined(VIDEO_ENABLED) && defined(ANDROID)
852                                 /*On android we have to disable the echo canceller to preserve CPU for video codecs */
853                                 if (vstream && vstream->dir!=SalStreamInactive && vstream->payloads!=NULL)
854                                         use_ec=FALSE;
855 #endif
856                                 audio_stream_start_full(
857                                         call->audiostream,
858                                         call->audio_profile,
859                                         stream->addr[0]!='\0' ? stream->addr : call->resultdesc->addr,
860                                         stream->port,
861                                         stream->port+1,
862                                         used_pt,
863                                         jitt_comp,
864                                         playfile,
865                                         recfile,
866                                         playcard,
867                                         captcard,
868                                         use_ec
869                                         );
870                                 post_configure_audio_streams(call);
871                                 if (all_inputs_muted && !send_ringbacktone){
872                                         audio_stream_set_mic_gain(call->audiostream,0);
873                                 }
874                                 if (stream->dir==SalStreamSendOnly && playfile!=NULL){
875                                         int pause_time=500;
876                                         ms_filter_call_method(call->audiostream->soundread,MS_FILE_PLAYER_LOOP,&pause_time);
877                                 }
878                                 if (send_ringbacktone){
879                                         setup_ring_player(lc,call);
880                                 }
881                                 audio_stream_set_rtcp_information(call->audiostream, cname, tool);
882                         }else ms_warning("No audio stream accepted ?");
883                 }
884         }
885 #ifdef VIDEO_ENABLED
886         {
887                 
888                 used_pt=-1;
889                 /* shutdown preview */
890                 if (lc->previewstream!=NULL) {
891                         video_preview_stop(lc->previewstream);
892                         lc->previewstream=NULL;
893                 }
894                 call->current_params.has_video=FALSE;
895                 if (vstream && vstream->dir!=SalStreamInactive) {
896                         const char *addr=vstream->addr[0]!='\0' ? vstream->addr : call->resultdesc->addr;
897                         call->video_profile=make_profile(call,call->resultdesc,vstream,&used_pt);
898                         if (used_pt!=-1){
899                                 VideoStreamDir dir=VideoStreamSendRecv;
900                                 MSWebCam *cam=lc->video_conf.device;
901                                 bool_t is_inactive=FALSE;
902
903                                 call->current_params.has_video=TRUE;
904                                 
905                                 video_stream_set_sent_video_size(call->videostream,linphone_core_get_preferred_video_size(lc));
906                                 video_stream_enable_self_view(call->videostream,lc->video_conf.selfview);
907                                 if (lc->video_window_id!=0)
908                                         video_stream_set_native_window_id(call->videostream,lc->video_window_id);
909                                 if (lc->preview_window_id!=0)
910                                         video_stream_set_native_preview_window_id (call->videostream,lc->preview_window_id);
911                                 video_stream_use_preview_video_window (call->videostream,lc->use_preview_window);
912                                 
913                                 if (vstream->dir==SalStreamSendOnly && lc->video_conf.capture ){
914                                         cam=get_nowebcam_device();
915                                         dir=VideoStreamSendOnly;
916                                 }else if (vstream->dir==SalStreamRecvOnly && lc->video_conf.display ){
917                                         dir=VideoStreamRecvOnly;
918                                 }else if (vstream->dir==SalStreamSendRecv){
919                                         if (lc->video_conf.display && lc->video_conf.capture)
920                                                 dir=VideoStreamSendRecv;
921                                         else if (lc->video_conf.display)
922                                                 dir=VideoStreamRecvOnly;
923                                         else
924                                                 dir=VideoStreamSendOnly;
925                                 }else{
926                                         ms_warning("video stream is inactive.");
927                                         /*either inactive or incompatible with local capabilities*/
928                                         is_inactive=TRUE;
929                                 }
930                                 if (call->camera_active==FALSE || all_inputs_muted){
931                                         cam=get_nowebcam_device();
932                                 }
933                                 if (!is_inactive){
934                                         video_stream_set_direction (call->videostream, dir);
935                                         video_stream_start(call->videostream,
936                                                 call->video_profile, addr, vstream->port,
937                                                 vstream->port+1,
938                                                 used_pt, jitt_comp, cam);
939                                         video_stream_set_rtcp_information(call->videostream, cname,tool);
940                                 }
941                         }else ms_warning("No video stream accepted.");
942                 }else{
943                         ms_warning("No valid video stream defined.");
944                 }
945         }
946 #endif
947         call->all_muted=all_inputs_muted;
948         call->playing_ringbacktone=send_ringbacktone;
949         call->up_bw=linphone_core_get_upload_bandwidth(lc);
950         
951         goto end;
952         end:
953                 ms_free(cname);
954                 linphone_address_destroy(me);
955 }
956
957 static void linphone_call_log_fill_stats(LinphoneCallLog *log, AudioStream *st){
958         audio_stream_get_local_rtp_stats (st,&log->local_stats);
959 }
960
961 void linphone_call_stop_media_streams(LinphoneCall *call){
962         if (call->audiostream!=NULL) {
963                 linphone_call_log_fill_stats (call->log,call->audiostream);
964                 audio_stream_stop(call->audiostream);
965                 call->audiostream=NULL;
966         }
967 #ifdef VIDEO_ENABLED
968         if (call->videostream!=NULL){
969                 video_stream_stop(call->videostream);
970                 call->videostream=NULL;
971         }
972         
973 #endif
974         if (call->audio_profile){
975                 rtp_profile_clear_all(call->audio_profile);
976                 rtp_profile_destroy(call->audio_profile);
977                 call->audio_profile=NULL;
978         }
979         if (call->video_profile){
980                 rtp_profile_clear_all(call->video_profile);
981                 rtp_profile_destroy(call->video_profile);
982                 call->video_profile=NULL;
983         }
984 }
985
986 #ifdef VIDEO_ENABLED
987 /**
988  * Request remote side to send us VFU.
989 **/
990 void linphone_call_send_vfu_request(LinphoneCall *call)
991 {
992         if (LinphoneCallStreamsRunning == linphone_call_get_state(call))
993                 sal_call_send_vfu_request(call->op);
994 }
995 #endif
996
997 void linphone_call_enable_echo_cancellation(LinphoneCall *call, bool_t enable) {
998         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
999                 bool_t bypass_mode = !enable;
1000                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_SET_BYPASS_MODE,&bypass_mode);
1001         }
1002 }
1003 bool_t linphone_call_echo_cancellation_enabled(LinphoneCall *call) {
1004         if (call!=NULL && call->audiostream!=NULL && call->audiostream->ec){
1005                 bool_t val;
1006                 ms_filter_call_method(call->audiostream->ec,MS_ECHO_CANCELLER_GET_BYPASS_MODE,&val);
1007                 return !val;
1008         } else {
1009                 return linphone_core_echo_cancellation_enabled(call->core);
1010         }
1011 }
1012
1013 void linphone_call_enable_echo_limiter(LinphoneCall *call, bool_t val){
1014         if (call!=NULL && call->audiostream!=NULL ) {
1015                 if (val) {
1016                 const char *type=lp_config_get_string(call->core->config,"sound","el_type","mic");
1017                 if (strcasecmp(type,"mic")==0)
1018                         audio_stream_enable_echo_limiter(call->audiostream,ELControlMic);
1019                 else if (strcasecmp(type,"full")==0)
1020                         audio_stream_enable_echo_limiter(call->audiostream,ELControlFull);
1021                 } else {
1022                         audio_stream_enable_echo_limiter(call->audiostream,ELInactive);
1023                 }
1024         }
1025 }
1026
1027 bool_t linphone_call_echo_limiter_enabled(const LinphoneCall *call){
1028         if (call!=NULL && call->audiostream!=NULL ){
1029                 return call->audiostream->el_type !=ELInactive ;
1030         } else {
1031                 return linphone_core_echo_limiter_enabled(call->core);
1032         }
1033 }
1034