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