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