]> sjero.net Git - linphone/blob - coreapi/callbacks.c
Keep the total number of streams and the number of active streams in the media descri...
[linphone] / coreapi / callbacks.c
1 /*
2 linphone
3 Copyright (C) 2010  Simon MORLAT (simon.morlat@free.fr)
4
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18 */
19
20
21 #include "sal.h"
22
23 #include "linphonecore.h"
24 #include "private.h"
25 #include "mediastreamer2/mediastream.h"
26 #include "lpconfig.h"
27
28 static void register_failure(SalOp *op, SalError error, SalReason reason, const char *details);
29
30 static int media_parameters_changed(LinphoneCall *call, SalMediaDescription *oldmd, SalMediaDescription *newmd) {
31         if (call->params.in_conference != call->current_params.in_conference) return SAL_MEDIA_DESCRIPTION_CHANGED;
32         if (call->up_bw != linphone_core_get_upload_bandwidth(call->core)) return SAL_MEDIA_DESCRIPTION_CHANGED;
33         return sal_media_description_equals(oldmd, newmd);
34 }
35
36 void linphone_core_update_streams_destinations(LinphoneCore *lc, LinphoneCall *call, SalMediaDescription *old_md, SalMediaDescription *new_md) {
37         SalStreamDescription *old_audiodesc = NULL;
38         SalStreamDescription *old_videodesc = NULL;
39         SalStreamDescription *new_audiodesc = NULL;
40         SalStreamDescription *new_videodesc = NULL;
41         char *rtp_addr, *rtcp_addr;
42         int i;
43
44         for (i = 0; i < old_md->n_active_streams; i++) {
45                 if (old_md->streams[i].type == SalAudio) {
46                         old_audiodesc = &old_md->streams[i];
47                 } else if (old_md->streams[i].type == SalVideo) {
48                         old_videodesc = &old_md->streams[i];
49                 }
50         }
51         for (i = 0; i < new_md->n_active_streams; i++) {
52                 if (new_md->streams[i].type == SalAudio) {
53                         new_audiodesc = &new_md->streams[i];
54                 } else if (new_md->streams[i].type == SalVideo) {
55                         new_videodesc = &new_md->streams[i];
56                 }
57         }
58         if (call->audiostream && new_audiodesc) {
59                 rtp_addr = (new_audiodesc->rtp_addr[0] != '\0') ? new_audiodesc->rtp_addr : new_md->addr;
60                 rtcp_addr = (new_audiodesc->rtcp_addr[0] != '\0') ? new_audiodesc->rtcp_addr : new_md->addr;
61                 ms_message("Change audio stream destination: RTP=%s:%d RTCP=%s:%d", rtp_addr, new_audiodesc->rtp_port, rtcp_addr, new_audiodesc->rtcp_port);
62                 rtp_session_set_remote_addr_full(call->audiostream->ms.session, rtp_addr, new_audiodesc->rtp_port, rtcp_addr, new_audiodesc->rtcp_port);
63         }
64 #ifdef VIDEO_ENABLED
65         if (call->videostream && new_videodesc) {
66                 rtp_addr = (new_videodesc->rtp_addr[0] != '\0') ? new_videodesc->rtp_addr : new_md->addr;
67                 rtcp_addr = (new_videodesc->rtcp_addr[0] != '\0') ? new_videodesc->rtcp_addr : new_md->addr;
68                 ms_message("Change video stream destination: RTP=%s:%d RTCP=%s:%d", rtp_addr, new_videodesc->rtp_port, rtcp_addr, new_videodesc->rtcp_port);
69                 rtp_session_set_remote_addr_full(call->videostream->ms.session, rtp_addr, new_videodesc->rtp_port, rtcp_addr, new_videodesc->rtcp_port);
70         }
71 #endif
72
73         /* Copy address and port values from new_md to old_md since we will keep old_md as resultdesc */
74         strcpy(old_md->addr, new_md->addr);
75         if (old_audiodesc && new_audiodesc) {
76                 strcpy(old_audiodesc->rtp_addr, new_audiodesc->rtp_addr);
77                 strcpy(old_audiodesc->rtcp_addr, new_audiodesc->rtcp_addr);
78                 old_audiodesc->rtp_port = new_audiodesc->rtp_port;
79                 old_audiodesc->rtcp_port = new_audiodesc->rtcp_port;
80         }
81         if (old_videodesc && new_videodesc) {
82                 strcpy(old_videodesc->rtp_addr, new_videodesc->rtp_addr);
83                 strcpy(old_videodesc->rtcp_addr, new_videodesc->rtcp_addr);
84                 old_videodesc->rtp_port = new_videodesc->rtp_port;
85                 old_videodesc->rtcp_port = new_videodesc->rtcp_port;
86         }
87 }
88
89 void linphone_core_update_streams(LinphoneCore *lc, LinphoneCall *call, SalMediaDescription *new_md){
90         SalMediaDescription *oldmd=call->resultdesc;
91         
92         if (lc->ringstream!=NULL){
93                 ring_stop(lc->ringstream);
94                 lc->ringstream=NULL;
95         }
96         if (new_md!=NULL){
97                 sal_media_description_ref(new_md);
98                 call->media_pending=FALSE;
99         }else{
100                 call->media_pending=TRUE;
101         }
102         call->resultdesc=new_md;
103         if ((call->audiostream && call->audiostream->ms.ticker) || (call->videostream && call->videostream->ms.ticker)){
104                 /* we already started media: check if we really need to restart it*/
105                 if (oldmd){
106                         int md_changed = media_parameters_changed(call, oldmd, new_md);
107                         if ((md_changed & SAL_MEDIA_DESCRIPTION_CODEC_CHANGED) || call->playing_ringbacktone) {
108                                 ms_message("Media descriptions are different, need to restart the streams.");
109                         } else {
110                                 if (md_changed == SAL_MEDIA_DESCRIPTION_UNCHANGED) {
111                                         /*as nothing has changed, keep the oldmd */
112                                         call->resultdesc=oldmd;
113                                         sal_media_description_unref(new_md);
114                                         if (call->all_muted){
115                                                 ms_message("Early media finished, unmuting inputs...");
116                                                 /*we were in early media, now we want to enable real media */
117                                                 linphone_call_enable_camera (call,linphone_call_camera_enabled (call));
118                                                 if (call->audiostream)
119                                                         linphone_core_mute_mic (lc, linphone_core_is_mic_muted(lc));
120 #ifdef VIDEO_ENABLED
121                                                 if (call->videostream && call->camera_active)
122                                                         video_stream_change_camera(call->videostream,lc->video_conf.device );
123 #endif
124                                         }
125                                         ms_message("No need to restart streams, SDP is unchanged.");
126                                         return;
127                                 }
128                                 else {
129                                         if (md_changed & SAL_MEDIA_DESCRIPTION_NETWORK_CHANGED) {
130                                                 ms_message("Network parameters have changed, update them.");
131                                                 linphone_core_update_streams_destinations(lc, call, oldmd, new_md);
132                                         }
133                                         if (md_changed & SAL_MEDIA_DESCRIPTION_CRYPTO_CHANGED) {
134                                                 ms_message("Crypto parameters have changed, update them.");
135                                                 linphone_call_update_crypto_parameters(call, oldmd, new_md);
136                                         }
137                                         call->resultdesc = oldmd;
138                                         sal_media_description_unref(new_md);
139                                         return;
140                                 }
141                         }
142                 }
143                 linphone_call_stop_media_streams (call);
144                 linphone_call_init_media_streams (call);
145         }
146         if (oldmd) 
147                 sal_media_description_unref(oldmd);
148         
149         if (new_md) {
150                 bool_t all_muted=FALSE;
151                 bool_t send_ringbacktone=FALSE;
152                 
153                 if (call->audiostream==NULL){
154                         /*this happens after pausing the call locally. The streams is destroyed and then we wait the 200Ok to recreate it*/
155                         linphone_call_init_media_streams (call);
156                 }
157                 if (call->state==LinphoneCallIncomingEarlyMedia && linphone_core_get_remote_ringback_tone (lc)!=NULL){
158                         send_ringbacktone=TRUE;
159                 }
160                 if (call->state==LinphoneCallIncomingEarlyMedia ||
161                     (call->state==LinphoneCallOutgoingEarlyMedia && !call->params.real_early_media)){
162                         all_muted=TRUE;
163                 }
164                 linphone_call_start_media_streams(call,all_muted,send_ringbacktone);
165         }
166 }
167 #if 0
168 static bool_t is_duplicate_call(LinphoneCore *lc, const LinphoneAddress *from, const LinphoneAddress *to){
169         MSList *elem;
170         for(elem=lc->calls;elem!=NULL;elem=elem->next){
171                 LinphoneCall *call=(LinphoneCall*)elem->data;
172                 if (linphone_address_weak_equal(call->log->from,from) &&
173                     linphone_address_weak_equal(call->log->to, to)){
174                         return TRUE;
175                 }
176         }
177         return FALSE;
178 }
179 #endif
180
181 static bool_t already_a_call_with_remote_address(const LinphoneCore *lc, const LinphoneAddress *remote) {
182         ms_warning(" searching for already_a_call_with_remote_address.");
183
184         MSList *elem;
185         for(elem=lc->calls;elem!=NULL;elem=elem->next){
186                 const LinphoneCall *call=(LinphoneCall*)elem->data;
187                 const LinphoneAddress *cRemote=linphone_call_get_remote_address(call);
188                 if (linphone_address_weak_equal(cRemote,remote)) {
189                         ms_warning("already_a_call_with_remote_address found.");
190                         return TRUE;
191                 }
192         }
193         return FALSE;
194 }
195
196 static bool_t already_a_call_pending(LinphoneCore *lc){
197         MSList *elem;
198         for(elem=lc->calls;elem!=NULL;elem=elem->next){
199                 LinphoneCall *call=(LinphoneCall*)elem->data;
200                 if (call->state==LinphoneCallIncomingReceived
201                     || call->state==LinphoneCallOutgoingInit
202                     || call->state==LinphoneCallOutgoingProgress
203                     || call->state==LinphoneCallOutgoingEarlyMedia
204                     || call->state==LinphoneCallOutgoingRinging){
205                         return TRUE;
206                 }
207         }
208         return FALSE;
209 }
210
211 static void call_received(SalOp *h){
212         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
213         LinphoneCall *call;
214         const char *from,*to;
215         LinphoneAddress *from_addr, *to_addr;
216         bool_t prevent_colliding_calls=lp_config_get_int(lc->config,"sip","prevent_colliding_calls",TRUE);
217         
218         /* first check if we can answer successfully to this invite */
219         if (lc->presence_mode==LinphoneStatusBusy ||
220             lc->presence_mode==LinphoneStatusOffline ||
221             lc->presence_mode==LinphoneStatusDoNotDisturb ||
222             lc->presence_mode==LinphoneStatusMoved){
223                 if (lc->presence_mode==LinphoneStatusBusy )
224                         sal_call_decline(h,SalReasonBusy,NULL);
225                 else if (lc->presence_mode==LinphoneStatusOffline)
226                         sal_call_decline(h,SalReasonTemporarilyUnavailable,NULL);
227                 else if (lc->presence_mode==LinphoneStatusDoNotDisturb)
228                         sal_call_decline(h,SalReasonTemporarilyUnavailable,NULL);
229                 else if (lc->alt_contact!=NULL && lc->presence_mode==LinphoneStatusMoved)
230                         sal_call_decline(h,SalReasonRedirect,lc->alt_contact);
231                 sal_op_release(h);
232                 return;
233         }
234         if (!linphone_core_can_we_add_call(lc)){/*busy*/
235                 sal_call_decline(h,SalReasonBusy,NULL);
236                 sal_op_release(h);
237                 return;
238         }
239         from=sal_op_get_from(h);
240         to=sal_op_get_to(h);
241         from_addr=linphone_address_new(from);
242         to_addr=linphone_address_new(to);
243
244         if ((already_a_call_with_remote_address(lc,from_addr) && prevent_colliding_calls) || already_a_call_pending(lc)){
245                 ms_warning("Receiving another call while one is ringing or initiated, refusing this one with busy message.");
246                 sal_call_decline(h,SalReasonBusy,NULL);
247                 sal_op_release(h);
248                 linphone_address_destroy(from_addr);
249                 linphone_address_destroy(to_addr);
250                 return;
251         }
252         
253         call=linphone_call_new_incoming(lc,from_addr,to_addr,h);
254         
255         /* the call is acceptable so we can now add it to our list */
256         linphone_core_add_call(lc,call);
257         linphone_call_ref(call); /*prevent the call from being destroyed while we are notifying, if the user declines within the state callback */
258
259         if ((linphone_core_get_firewall_policy(lc) == LinphonePolicyUseIce) && (call->ice_session != NULL)) {
260                 /* Defer ringing until the end of the ICE candidates gathering process. */
261                 ms_message("Defer ringing to gather ICE candidates");
262                 return;
263         }
264
265         linphone_core_notify_incoming_call(lc,call);
266 }
267
268 static void call_ringing(SalOp *h){
269         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
270         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(h);
271         SalMediaDescription *md;
272         
273         if (call==NULL) return;
274         
275         if (lc->vtable.display_status)
276                 lc->vtable.display_status(lc,_("Remote ringing."));
277         
278         md=sal_call_get_final_media_description(h);
279         if (md==NULL){
280                 if (lc->ringstream && lc->dmfs_playing_start_time!=0){
281                         ring_stop(lc->ringstream);
282                         lc->ringstream=NULL;
283                         lc->dmfs_playing_start_time=0;
284                 }
285                 if (lc->ringstream!=NULL) return;       /*already ringing !*/
286                 if (lc->sound_conf.play_sndcard!=NULL){
287                         MSSndCard *ringcard=lc->sound_conf.lsd_card ? lc->sound_conf.lsd_card : lc->sound_conf.play_sndcard;
288                         if (call->localdesc->streams[0].max_rate>0) ms_snd_card_set_preferred_sample_rate(ringcard, call->localdesc->streams[0].max_rate);
289                         /*we release sound before playing ringback tone*/
290                         if (call->audiostream)
291                                 audio_stream_unprepare_sound(call->audiostream);
292                         lc->ringstream=ring_start(lc->sound_conf.remote_ring,2000,ringcard);
293                 }
294                 ms_message("Remote ringing...");
295                 if (lc->vtable.display_status) 
296                         lc->vtable.display_status(lc,_("Remote ringing..."));
297                 linphone_call_set_state(call,LinphoneCallOutgoingRinging,"Remote ringing");
298         }else{
299                 /*accept early media */
300                 if (call->audiostream && audio_stream_started(call->audiostream)){
301                         /*streams already started */
302                         ms_message("Early media already started.");
303                         return;
304                 }
305                 if (lc->vtable.show) lc->vtable.show(lc);
306                 if (lc->vtable.display_status) 
307                         lc->vtable.display_status(lc,_("Early media."));
308                 linphone_call_set_state(call,LinphoneCallOutgoingEarlyMedia,"Early media");
309                 if (lc->ringstream!=NULL){
310                         ring_stop(lc->ringstream);
311                         lc->ringstream=NULL;
312                 }
313                 ms_message("Doing early media...");
314                 linphone_core_update_streams(lc,call,md);
315         }
316 }
317
318 /*
319  * could be reach :
320  *  - when the call is accepted
321  *  - when a request is accepted (pause, resume)
322  */
323 static void call_accepted(SalOp *op){
324         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
325         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
326         SalMediaDescription *md;
327         
328         if (call==NULL){
329                 ms_warning("No call to accept.");
330                 return ;
331         }
332
333         /* Handle remote ICE attributes if any. */
334         if (call->ice_session != NULL) {
335                 linphone_core_update_ice_from_remote_media_description(call, sal_call_get_remote_media_description(op));
336         }
337
338         md=sal_call_get_final_media_description(op);
339         call->params.has_video &= linphone_core_media_description_contains_video_stream(md);
340         
341         if (call->state==LinphoneCallOutgoingProgress ||
342             call->state==LinphoneCallOutgoingRinging ||
343             call->state==LinphoneCallOutgoingEarlyMedia){
344                 linphone_call_set_state(call,LinphoneCallConnected,"Connected");
345                 if (call->referer) linphone_core_notify_refer_state(lc,call->referer,call);
346         }
347         if (md && !sal_media_description_empty(md) && !linphone_core_incompatible_security(lc,md)){
348                 linphone_call_update_remote_session_id_and_ver(call);
349                 if (sal_media_description_has_dir(md,SalStreamSendOnly) ||
350                     sal_media_description_has_dir(md,SalStreamInactive)){
351                         if (lc->vtable.display_status){
352                                 char *tmp=linphone_call_get_remote_address_as_string (call);
353                                 char *msg=ms_strdup_printf(_("Call with %s is paused."),tmp);
354                                 lc->vtable.display_status(lc,msg);
355                                 ms_free(tmp);
356                                 ms_free(msg);
357                         }
358                         linphone_core_update_streams (lc,call,md);
359                         linphone_call_set_state(call,LinphoneCallPaused,"Call paused");
360                         if (call->refer_pending)
361                                 linphone_core_start_refered_call(lc,call);
362                 }else if (sal_media_description_has_dir(md,SalStreamRecvOnly)){
363                         /*we are put on hold when the call is initially accepted */
364                         if (lc->vtable.display_status){
365                                 char *tmp=linphone_call_get_remote_address_as_string (call);
366                                 char *msg=ms_strdup_printf(_("Call answered by %s - on hold."),tmp);
367                                 lc->vtable.display_status(lc,msg);
368                                 ms_free(tmp);
369                                 ms_free(msg);
370                         }
371                         linphone_core_update_streams (lc,call,md);
372                         linphone_call_set_state(call,LinphoneCallPausedByRemote,"Call paused by remote");
373                 }else{
374                         if (call->state!=LinphoneCallUpdating){
375                                 if (call->state==LinphoneCallResuming){
376                                         if (lc->vtable.display_status){
377                                                 lc->vtable.display_status(lc,_("Call resumed."));
378                                         }
379                                 }else{
380                                         if (lc->vtable.display_status){
381                                                 char *tmp=linphone_call_get_remote_address_as_string (call);
382                                                 char *msg=ms_strdup_printf(_("Call answered by %s."),tmp);
383                                                 lc->vtable.display_status(lc,msg);
384                                                 ms_free(tmp);
385                                                 ms_free(msg);
386                                         }
387                                 }
388                         }
389                         linphone_core_update_streams (lc,call,md);
390                         if (!call->current_params.in_conference)
391                                 lc->current_call=call;
392                         linphone_call_set_state(call, LinphoneCallStreamsRunning, "Streams running");
393                 }
394         }else{
395                 /*send a bye*/
396                 ms_error("Incompatible SDP offer received in 200Ok, need to abort the call");
397                 linphone_core_abort_call(lc,call,_("Incompatible, check codecs or security settings..."));
398         }
399 }
400
401 static void call_ack(SalOp *op){
402         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
403         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
404         if (call==NULL){
405                 ms_warning("No call to be ACK'd");
406                 return ;
407         }
408         if (call->media_pending){
409                 SalMediaDescription *md=sal_call_get_final_media_description(op);
410                 if (md && !sal_media_description_empty(md)){
411                         linphone_core_update_streams (lc,call,md);
412                         linphone_call_set_state (call,LinphoneCallStreamsRunning,"Connected (streams running)");
413                 }else{
414                         /*send a bye*/
415                         ms_error("Incompatible SDP response received in ACK, need to abort the call");
416                         linphone_core_abort_call(lc,call,"No codec intersection");
417                         return;
418                 }
419         }
420 }
421
422 static void call_accept_update(LinphoneCore *lc, LinphoneCall *call){
423         SalMediaDescription *md;
424         SalMediaDescription *rmd=sal_call_get_remote_media_description(call->op);
425         if ((rmd!=NULL) && (call->ice_session!=NULL)) {
426                 linphone_core_update_ice_from_remote_media_description(call,rmd);
427                 linphone_core_update_local_media_description_from_ice(call->localdesc,call->ice_session);
428         }
429         linphone_call_update_remote_session_id_and_ver(call);
430         sal_call_accept(call->op);
431         md=sal_call_get_final_media_description(call->op);
432         if (md && !sal_media_description_empty(md))
433                 linphone_core_update_streams(lc,call,md);
434 }
435
436 static void call_resumed(LinphoneCore *lc, LinphoneCall *call){
437         call_accept_update(lc,call);
438         if(lc->vtable.display_status)
439                 lc->vtable.display_status(lc,_("We have been resumed."));
440         linphone_call_set_state(call,LinphoneCallStreamsRunning,"Connected (streams running)");
441         linphone_call_set_transfer_state(call, LinphoneCallIdle);
442 }
443
444 static void call_paused_by_remote(LinphoneCore *lc, LinphoneCall *call){
445         call_accept_update(lc,call);
446         /* we are being paused */
447         if(lc->vtable.display_status)
448                 lc->vtable.display_status(lc,_("We are paused by other party."));
449         linphone_call_set_state (call,LinphoneCallPausedByRemote,"Call paused by remote");
450 }
451
452 static void call_updated_by_remote(LinphoneCore *lc, LinphoneCall *call){
453         if(lc->vtable.display_status)
454                 lc->vtable.display_status(lc,_("Call is updated by remote."));
455         call->defer_update=FALSE;
456         linphone_call_set_state(call, LinphoneCallUpdatedByRemote,"Call updated by remote");
457         if (call->defer_update==FALSE){
458                 linphone_core_accept_call_update(lc,call,NULL);
459         }
460 }
461
462 /* this callback is called when an incoming re-INVITE modifies the session*/
463 static void call_updating(SalOp *op){
464         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
465         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
466         SalMediaDescription *rmd=sal_call_get_remote_media_description(op);
467
468         if (rmd==NULL){
469                 /* case of a reINVITE without SDP */
470                 call_accept_update(lc,call);
471                 call->media_pending=TRUE;
472                 return;
473         }
474
475         switch(call->state){
476                 case LinphoneCallPausedByRemote:
477                         if (sal_media_description_has_dir(rmd,SalStreamSendRecv) || sal_media_description_has_dir(rmd,SalStreamRecvOnly)){
478                                 call_resumed(lc,call);
479                         }else call_paused_by_remote(lc,call);
480                 break;
481                 case LinphoneCallStreamsRunning:
482                 case LinphoneCallConnected:
483                         if (sal_media_description_has_dir(rmd,SalStreamSendOnly) || sal_media_description_has_dir(rmd,SalStreamInactive)){
484                                 call_paused_by_remote(lc,call);
485                         }else{
486                                 call_updated_by_remote(lc,call);
487                         }
488                 break;
489                 default:
490                         call_accept_update(lc,call);
491         }
492 }
493
494 static void call_terminated(SalOp *op, const char *from){
495         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
496         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
497
498         if (call==NULL) return;
499         
500         switch(linphone_call_get_state(call)){
501                 case LinphoneCallEnd:
502                 case LinphoneCallError:
503                         ms_warning("call_terminated: ignoring.");
504                         return;
505                 break;
506                 case LinphoneCallIncomingReceived:
507                 case LinphoneCallIncomingEarlyMedia:
508                         call->reason=LinphoneReasonNotAnswered;
509                 break;
510                 default:
511                 break;
512         }
513         ms_message("Current call terminated...");
514         //we stop the call only if we have this current call or if we are in call
515         if (lc->ringstream!=NULL && ( (ms_list_size(lc->calls)  == 1) || linphone_core_in_call(lc) )) {
516                 ring_stop(lc->ringstream);
517                 lc->ringstream=NULL;
518         }
519         linphone_call_stop_media_streams(call);
520         if (lc->vtable.show!=NULL)
521                 lc->vtable.show(lc);
522         if (lc->vtable.display_status!=NULL)
523                 lc->vtable.display_status(lc,_("Call terminated."));
524
525         linphone_call_set_state(call, LinphoneCallEnd,"Call ended");
526 }
527
528 static void call_failure(SalOp *op, SalError error, SalReason sr, const char *details, int code){
529         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
530         char *msg486=_("User is busy.");
531         char *msg480=_("User is temporarily unavailable.");
532         /*char *retrymsg=_("%s. Retry after %i minute(s).");*/
533         char *msg600=_("User does not want to be disturbed.");
534         char *msg603=_("Call declined.");
535         const char *msg=details;
536         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
537
538         if (call==NULL){
539                 ms_warning("Call faillure reported on already cleaned call ?");
540                 return ;
541         }
542         
543         if (lc->vtable.show) lc->vtable.show(lc);
544
545         if (error==SalErrorNoResponse){
546                 msg=_("No response.");
547                 if (lc->vtable.display_status)
548                         lc->vtable.display_status(lc,msg);
549         }else if (error==SalErrorProtocol){
550                 msg=details ? details : _("Protocol error.");
551                 if (lc->vtable.display_status)
552                         lc->vtable.display_status(lc, msg);
553         }else if (error==SalErrorFailure){
554                 switch(sr){
555                         case SalReasonDeclined:
556                                 msg=msg603;
557                                 if (lc->vtable.display_status)
558                                         lc->vtable.display_status(lc,msg603);
559                         break;
560                         case SalReasonBusy:
561                                 msg=msg486;
562                                 if (lc->vtable.display_status)
563                                         lc->vtable.display_status(lc,msg486);
564                         break;
565                         case SalReasonRedirect:
566                                 msg=_("Redirected");
567                                 if (lc->vtable.display_status)
568                                         lc->vtable.display_status(lc,msg);
569                         break;
570                         case SalReasonTemporarilyUnavailable:
571                                 msg=msg480;
572                                 if (lc->vtable.display_status)
573                                         lc->vtable.display_status(lc,msg480);
574                         break;
575                         case SalReasonNotFound:
576                                 if (lc->vtable.display_status)
577                                         lc->vtable.display_status(lc,msg);
578                         break;
579                         case SalReasonDoNotDisturb:
580                                 msg=msg600;
581                                 if (lc->vtable.display_status)
582                                         lc->vtable.display_status(lc,msg600);
583                         break;
584                         case SalReasonMedia:
585                         //media_encryption_mandatory
586                                 if (call->params.media_encryption == LinphoneMediaEncryptionSRTP && 
587                                         !linphone_core_is_media_encryption_mandatory(lc)) {
588                                         int i;
589                                         ms_message("Outgoing call failed with SRTP (SAVP) enabled - retrying with AVP");
590                                         linphone_call_stop_media_streams(call);
591                                         if (call->state==LinphoneCallOutgoingInit || call->state==LinphoneCallOutgoingProgress){
592                                                 /* clear SRTP local params */
593                                                 call->params.media_encryption = LinphoneMediaEncryptionNone;
594                                                 for(i=0; i<call->localdesc->n_active_streams; i++) {
595                                                         call->localdesc->streams[i].proto = SalProtoRtpAvp;
596                                                         memset(call->localdesc->streams[i].crypto, 0, sizeof(call->localdesc->streams[i].crypto));
597                                                 }
598                                                 linphone_core_start_invite(lc, call);
599                                         }
600                                         return;
601                                 }
602                                 msg=_("Incompatible media parameters.");
603                                 if (lc->vtable.display_status)
604                                         lc->vtable.display_status(lc,msg);
605                         break;
606                         default:
607                                 if (lc->vtable.display_status)
608                                         lc->vtable.display_status(lc,_("Call failed."));
609                 }
610         }
611
612         if (lc->ringstream!=NULL) {
613                 ring_stop(lc->ringstream);
614                 lc->ringstream=NULL;
615         }
616         linphone_call_stop_media_streams (call);
617         if (call->referer && linphone_call_get_state(call->referer)==LinphoneCallPaused && call->referer->was_automatically_paused){
618                 /*resume to the call that send us the refer automatically*/
619                 linphone_core_resume_call(lc,call->referer);
620         }
621         if (sr == SalReasonDeclined) {
622                 call->reason=LinphoneReasonDeclined;
623                 linphone_call_set_state(call,LinphoneCallEnd,"Call declined.");
624         } else if (sr == SalReasonNotFound) {
625                 call->reason=LinphoneReasonNotFound;
626                 linphone_call_set_state(call,LinphoneCallError,"User not found.");
627         } else {
628                 linphone_call_set_state(call,LinphoneCallError,msg);
629         }
630 }
631
632 static void call_released(SalOp *op){
633         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
634         if (call!=NULL){
635                 linphone_call_set_state(call,LinphoneCallReleased,"Call released");
636         }else ms_error("call_released() for already destroyed call ?");
637 }
638
639 static void auth_requested(SalOp *h, const char *realm, const char *username){
640         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
641         LinphoneAuthInfo *ai=(LinphoneAuthInfo*)linphone_core_find_auth_info(lc,realm,username);
642         LinphoneCall *call=is_a_linphone_call(sal_op_get_user_pointer(h));
643
644         if (call && call->ping_op==h){
645                 /*don't request authentication for ping requests. Their purpose is just to get any
646                  * answer to get the Via's received and rport parameters.
647                  */
648                 ms_message("auth_requested(): ignored for ping request.");
649                 return;
650         }
651         
652         ms_message("auth_requested() for realm=%s, username=%s",realm,username);
653
654         if (ai && ai->works==FALSE && ai->usecount>=3){
655                 /*case we tried 3 times to authenticate, without success */
656                 /*Better is to stop (implemeted below in else statement), and retry later*/
657                 if (ms_time(NULL)-ai->last_use_time>30){
658                         ai->usecount=0; /*so that we can allow to retry */
659                 }
660         }
661         
662         if (ai && (ai->works || ai->usecount<3)){
663                 SalAuthInfo sai;
664                 sai.username=ai->username;
665                 sai.userid=ai->userid;
666                 sai.realm=ai->realm;
667                 sai.password=ai->passwd;
668                 ms_message("auth_requested(): authenticating realm=%s, username=%s",realm,username);
669                 sal_op_authenticate(h,&sai);
670                 ai->usecount++;
671                 ai->last_use_time=ms_time(NULL);
672         }else{
673                 if (ai && ai->works==FALSE) {
674                         sal_op_cancel_authentication(h);
675                 } 
676                 if (lc->vtable.auth_info_requested)
677                         lc->vtable.auth_info_requested(lc,realm,username);
678         }
679 }
680
681 static void auth_success(SalOp *h, const char *realm, const char *username){
682         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(h));
683         LinphoneAuthInfo *ai=(LinphoneAuthInfo*)linphone_core_find_auth_info(lc,realm,username);
684         if (ai){
685                 ms_message("%s/%s authentication works.",realm,username);
686                 ai->works=TRUE;
687         }
688 }
689
690 static void register_success(SalOp *op, bool_t registered){
691         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
692         LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)sal_op_get_user_pointer(op);
693         char *msg;
694         
695         if (cfg->deletion_date!=0){
696                 ms_message("Registration success for removed proxy config, ignored");
697                 return;
698         }
699         linphone_proxy_config_set_error(cfg,LinphoneReasonNone);
700         linphone_proxy_config_set_state(cfg, registered ? LinphoneRegistrationOk : LinphoneRegistrationCleared ,
701                                         registered ? "Registration sucessful" : "Unregistration done");
702         if (lc->vtable.display_status){
703                 if (registered) msg=ms_strdup_printf(_("Registration on %s successful."),sal_op_get_proxy(op));
704                 else msg=ms_strdup_printf(_("Unregistration on %s done."),sal_op_get_proxy(op));
705                 lc->vtable.display_status(lc,msg);
706                 ms_free(msg);
707         }
708         
709 }
710
711 static void register_failure(SalOp *op, SalError error, SalReason reason, const char *details){
712         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
713         LinphoneProxyConfig *cfg=(LinphoneProxyConfig*)sal_op_get_user_pointer(op);
714
715         if (cfg==NULL){
716                 ms_warning("Registration failed for unknown proxy config.");
717                 return ;
718         }
719         if (cfg->deletion_date!=0){
720                 ms_message("Registration failed for removed proxy config, ignored");
721                 return;
722         }
723         if (details==NULL)
724                 details=_("no response timeout");
725         
726         if (lc->vtable.display_status) {
727                 char *msg=ortp_strdup_printf(_("Registration on %s failed: %s"),sal_op_get_proxy(op),details  );
728                 lc->vtable.display_status(lc,msg);
729                 ms_free(msg);
730         }
731         if (error== SalErrorFailure && reason == SalReasonForbidden) {
732                 linphone_proxy_config_set_error(cfg, LinphoneReasonBadCredentials);
733         } else if (error == SalErrorNoResponse) {
734                 linphone_proxy_config_set_error(cfg, LinphoneReasonNoResponse);
735         }
736         linphone_proxy_config_set_state(cfg,LinphoneRegistrationFailed,details);
737         if (error== SalErrorFailure && reason == SalReasonForbidden) {
738                 const char *realm=NULL,*username=NULL;
739                 if (sal_op_get_auth_requested(op,&realm,&username)==0){
740                         if (lc->vtable.auth_info_requested)
741                                 lc->vtable.auth_info_requested(lc,realm,username);
742                 }
743         }
744 }
745
746 static void vfu_request(SalOp *op){
747 #ifdef VIDEO_ENABLED
748         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer (op);
749         if (call==NULL){
750                 ms_warning("VFU request but no call !");
751                 return ;
752         }
753         if (call->videostream)
754                 video_stream_send_vfu(call->videostream);
755 #endif
756 }
757
758 static void dtmf_received(SalOp *op, char dtmf){
759         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
760         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
761         if (lc->vtable.dtmf_received != NULL)
762                 lc->vtable.dtmf_received(lc, call, dtmf);
763 }
764
765 static void refer_received(Sal *sal, SalOp *op, const char *referto){
766         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal);
767         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer(op);
768         if (call){
769                 if (call->refer_to!=NULL){
770                         ms_free(call->refer_to);
771                 }
772                 call->refer_to=ms_strdup(referto);
773                 call->refer_pending=TRUE;
774                 linphone_call_set_state(call,LinphoneCallRefered,"Refered");
775                 if (lc->vtable.display_status){
776                         char *msg=ms_strdup_printf(_("We are transferred to %s"),referto);
777                         lc->vtable.display_status(lc,msg);
778                         ms_free(msg);
779                 }
780                 if (call->state!=LinphoneCallPaused){
781                         ms_message("Automatically pausing current call to accept transfer.");
782                         linphone_core_pause_call(lc,call);
783                         call->was_automatically_paused=TRUE;
784                         /*then we will start the refered when the pause is accepted, in order to serialize transactions within the dialog.
785                          * Indeed we need to avoid to send a NOTIFY to inform about of state of the refered call while the pause isn't completed.
786                         **/
787                 }else linphone_core_start_refered_call(lc,call);
788         }else if (lc->vtable.refer_received){
789                 lc->vtable.refer_received(lc,referto);
790         }
791 }
792
793 static bool_t is_duplicate_msg(LinphoneCore *lc, const char *msg_id){
794         MSList *elem=lc->last_recv_msg_ids;
795         MSList *tail=NULL;
796         int i;
797         bool_t is_duplicate=FALSE;
798         for(i=0;elem!=NULL;elem=elem->next,i++){
799                 if (strcmp((const char*)elem->data,msg_id)==0){
800                         is_duplicate=TRUE;
801                 }
802                 tail=elem;
803         }
804         if (!is_duplicate){
805                 lc->last_recv_msg_ids=ms_list_prepend(lc->last_recv_msg_ids,ms_strdup(msg_id));
806         }
807         if (i>=10){
808                 ms_free(tail->data);
809                 lc->last_recv_msg_ids=ms_list_remove_link(lc->last_recv_msg_ids,tail);
810         }
811         return is_duplicate;
812 }
813
814
815 static void text_received(Sal *sal, const SalMessage *msg){
816         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal);
817         if (is_duplicate_msg(lc,msg->message_id)==FALSE){
818                 linphone_core_message_received(lc,msg->from,msg->text,msg->url);
819         }
820 }
821
822 static void notify(SalOp *op, const char *from, const char *msg){
823         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
824         LinphoneCall *call=(LinphoneCall*)sal_op_get_user_pointer (op);
825         ms_message("get a %s notify from %s",msg,from);
826         if(lc->vtable.notify_recv)
827                 lc->vtable.notify_recv(lc,call,from,msg);
828 }
829
830 static void notify_presence(SalOp *op, SalSubscribeStatus ss, SalPresenceStatus status, const char *msg){
831         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
832         linphone_notify_recv(lc,op,ss,status);
833 }
834
835 static void subscribe_received(SalOp *op, const char *from){
836         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
837         linphone_subscription_new(lc,op,from);
838 }
839
840 static void subscribe_closed(SalOp *op, const char *from){
841         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
842         linphone_subscription_closed(lc,op);
843 }
844
845 static void ping_reply(SalOp *op){
846         LinphoneCall *call=(LinphoneCall*) sal_op_get_user_pointer(op);
847         ms_message("ping reply !");
848         if (call){
849                 if (call->state==LinphoneCallOutgoingInit){
850                         call->ping_replied=TRUE;
851                         linphone_core_proceed_with_invite_if_ready(call->core,call,NULL);
852                 }
853         }
854         else
855         {
856                 ms_warning("ping reply without call attached...");
857         }
858 }
859
860 static void notify_refer(SalOp *op, SalReferStatus status){
861         LinphoneCore *lc=(LinphoneCore *)sal_get_user_pointer(sal_op_get_sal(op));
862         LinphoneCall *call=(LinphoneCall*) sal_op_get_user_pointer(op);
863         LinphoneCallState cstate;
864         if (call==NULL) {
865                 ms_warning("Receiving notify_refer for unknown call.");
866                 return ;
867         }
868         switch(status){
869                 case SalReferTrying:
870                         cstate=LinphoneCallOutgoingProgress;
871                 break;
872                 case SalReferSuccess:
873                         cstate=LinphoneCallConnected;
874                 break;
875                 case SalReferFailed:
876                         cstate=LinphoneCallError;
877                 break;
878                 default:
879                         cstate=LinphoneCallError;
880         }
881         linphone_call_set_transfer_state(call, cstate);
882         if (cstate==LinphoneCallConnected){
883                 /*automatically terminate the call as the transfer is complete.*/
884                 linphone_core_terminate_call(lc,call);
885         }
886 }
887
888 static LinphoneChatMessageState chatStatusSal2Linphone(SalTextDeliveryStatus status){
889         switch(status){
890                 case SalTextDeliveryInProgress:
891                         return LinphoneChatMessageStateInProgress;
892                 case SalTextDeliveryDone:
893                         return LinphoneChatMessageStateDelivered;
894                 case SalTextDeliveryFailed:
895                         return LinphoneChatMessageStateNotDelivered;
896         }
897         return LinphoneChatMessageStateIdle;
898 }
899
900 static int op_equals(LinphoneCall *a, SalOp *b) {
901         return a->op !=b; /*return 0 if equals*/
902 }
903 static void text_delivery_update(SalOp *op, SalTextDeliveryStatus status){
904         LinphoneChatMessage *chat_msg=(LinphoneChatMessage* )sal_op_get_user_pointer(op);
905         const MSList* calls = linphone_core_get_calls(chat_msg->chat_room->lc);
906         
907         if (chat_msg && chat_msg->cb) {
908                 chat_msg->cb(chat_msg
909                         ,chatStatusSal2Linphone(status)
910                         ,chat_msg->cb_ud);
911         }
912         linphone_chat_message_destroy(chat_msg);
913         
914         if (!ms_list_find_custom((MSList*)calls, (MSCompareFunc) op_equals, op)) {
915                 /*op was only create for messaging purpose, destroying*/
916                 sal_op_release(op);
917         }
918 }
919
920 SalCallbacks linphone_sal_callbacks={
921         call_received,
922         call_ringing,
923         call_accepted,
924         call_ack,
925         call_updating,
926         call_terminated,
927         call_failure,
928         call_released,
929         auth_requested,
930         auth_success,
931         register_success,
932         register_failure,
933         vfu_request,
934         dtmf_received,
935         refer_received,
936         text_received,
937         text_delivery_update,
938         notify,
939         notify_presence,
940         notify_refer,
941         subscribe_received,
942         subscribe_closed,
943         ping_reply,
944 };
945
946