1package eu.siacs.conversations.xmpp.jingle;
2
3import android.util.Log;
4
5import com.google.common.collect.ImmutableList;
6import com.google.common.collect.ImmutableMap;
7
8import org.webrtc.IceCandidate;
9import org.webrtc.PeerConnection;
10
11import java.util.ArrayDeque;
12import java.util.Arrays;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.List;
16import java.util.Map;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.xml.Element;
20import eu.siacs.conversations.xml.Namespace;
21import eu.siacs.conversations.xmpp.jingle.stanzas.Group;
22import eu.siacs.conversations.xmpp.jingle.stanzas.IceUdpTransportInfo;
23import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
24import eu.siacs.conversations.xmpp.jingle.stanzas.Reason;
25import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
26import rocks.xmpp.addr.Jid;
27
28public class JingleRtpConnection extends AbstractJingleConnection implements WebRTCWrapper.EventCallback {
29
30 private static final Map<State, Collection<State>> VALID_TRANSITIONS;
31
32 static {
33 final ImmutableMap.Builder<State, Collection<State>> transitionBuilder = new ImmutableMap.Builder<>();
34 transitionBuilder.put(State.NULL, ImmutableList.of(State.PROPOSED, State.SESSION_INITIALIZED));
35 transitionBuilder.put(State.PROPOSED, ImmutableList.of(State.ACCEPTED, State.PROCEED, State.REJECTED, State.RETRACTED));
36 transitionBuilder.put(State.PROCEED, ImmutableList.of(State.SESSION_INITIALIZED));
37 transitionBuilder.put(State.SESSION_INITIALIZED, ImmutableList.of(State.SESSION_ACCEPTED));
38 VALID_TRANSITIONS = transitionBuilder.build();
39 }
40
41 private final WebRTCWrapper webRTCWrapper = new WebRTCWrapper(this);
42 private final ArrayDeque<IceCandidate> pendingIceCandidates = new ArrayDeque<>();
43 private State state = State.NULL;
44 private RtpContentMap initiatorRtpContentMap;
45 private RtpContentMap responderRtpContentMap;
46
47
48 public JingleRtpConnection(JingleConnectionManager jingleConnectionManager, Id id, Jid initiator) {
49 super(jingleConnectionManager, id, initiator);
50 }
51
52 @Override
53 void deliverPacket(final JinglePacket jinglePacket) {
54 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": packet delivered to JingleRtpConnection");
55 switch (jinglePacket.getAction()) {
56 case SESSION_INITIATE:
57 receiveSessionInitiate(jinglePacket);
58 break;
59 case TRANSPORT_INFO:
60 receiveTransportInfo(jinglePacket);
61 break;
62 case SESSION_ACCEPT:
63 receiveSessionAccept(jinglePacket);
64 break;
65 case SESSION_TERMINATE:
66 receiveSessionTerminate(jinglePacket);
67 break;
68 default:
69 Log.d(Config.LOGTAG, String.format("%s: received unhandled jingle action %s", id.account.getJid().asBareJid(), jinglePacket.getAction()));
70 break;
71 }
72 }
73
74 private void receiveSessionTerminate(final JinglePacket jinglePacket) {
75 final Reason reason = jinglePacket.getReason();
76 switch (reason) {
77 case SUCCESS:
78 transitionOrThrow(State.TERMINATED_SUCCESS);
79 break;
80 case DECLINE:
81 case BUSY:
82 transitionOrThrow(State.TERMINATED_DECLINED_OR_BUSY);
83 break;
84 case CANCEL:
85 case TIMEOUT:
86 transitionOrThrow(State.TERMINATED_CANCEL_OR_TIMEOUT);
87 break;
88 default:
89 transitionOrThrow(State.TERMINATED_CONNECTIVITY_ERROR);
90 break;
91 }
92 jingleConnectionManager.finishConnection(this);
93 }
94
95 private void receiveTransportInfo(final JinglePacket jinglePacket) {
96 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
97 final RtpContentMap contentMap;
98 try {
99 contentMap = RtpContentMap.of(jinglePacket);
100 } catch (IllegalArgumentException | NullPointerException e) {
101 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
102 return;
103 }
104 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
105 final Group originalGroup = rtpContentMap != null ? rtpContentMap.group : null;
106 final List<String> identificationTags = originalGroup == null ? Collections.emptyList() : originalGroup.getIdentificationTags();
107 if (identificationTags.size() == 0) {
108 Log.w(Config.LOGTAG, id.account.getJid().asBareJid() + ": no identification tags found in initial offer. we won't be able to calculate mLineIndices");
109 }
110 for (final Map.Entry<String, RtpContentMap.DescriptionTransport> content : contentMap.contents.entrySet()) {
111 final String ufrag = content.getValue().transport.getAttribute("ufrag");
112 for (final IceUdpTransportInfo.Candidate candidate : content.getValue().transport.getCandidates()) {
113 final String sdp = candidate.toSdpAttribute(ufrag);
114 final String sdpMid = content.getKey();
115 final int mLineIndex = identificationTags.indexOf(sdpMid);
116 final IceCandidate iceCandidate = new IceCandidate(sdpMid, mLineIndex, sdp);
117 Log.d(Config.LOGTAG, "received candidate: " + iceCandidate);
118 if (isInState(State.SESSION_ACCEPTED)) {
119 this.webRTCWrapper.addIceCandidate(iceCandidate);
120 } else {
121 this.pendingIceCandidates.push(iceCandidate);
122 }
123 }
124 }
125 } else {
126 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received transport info while in state=" + this.state);
127 }
128 }
129
130 private void receiveSessionInitiate(final JinglePacket jinglePacket) {
131 if (isInitiator()) {
132 Log.d(Config.LOGTAG, String.format("%s: received session-initiate even though we were initiating", id.account.getJid().asBareJid()));
133 //TODO respond with out-of-order
134 return;
135 }
136 final RtpContentMap contentMap;
137 try {
138 contentMap = RtpContentMap.of(jinglePacket);
139 contentMap.requireContentDescriptions();
140 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
141 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
142 return;
143 }
144 Log.d(Config.LOGTAG, "processing session-init with " + contentMap.contents.size() + " contents");
145 final State oldState = this.state;
146 if (transition(State.SESSION_INITIALIZED)) {
147 this.initiatorRtpContentMap = contentMap;
148 if (oldState == State.PROCEED) {
149 Log.d(Config.LOGTAG, "automatically accepting");
150 sendSessionAccept();
151 } else {
152 Log.d(Config.LOGTAG, "start ringing");
153 //TODO start ringing
154 }
155 } else {
156 Log.d(Config.LOGTAG, String.format("%s: received session-initiate while in state %s", id.account.getJid().asBareJid(), state));
157 }
158 }
159
160 private void receiveSessionAccept(final JinglePacket jinglePacket) {
161 if (!isInitiator()) {
162 Log.d(Config.LOGTAG, String.format("%s: received session-accept even though we were responding", id.account.getJid().asBareJid()));
163 //TODO respond with out-of-order
164 return;
165 }
166 final RtpContentMap contentMap;
167 try {
168 contentMap = RtpContentMap.of(jinglePacket);
169 contentMap.requireContentDescriptions();
170 } catch (IllegalArgumentException | IllegalStateException | NullPointerException e) {
171 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": improperly formatted contents", e);
172 return;
173 }
174 Log.d(Config.LOGTAG, "processing session-accept with " + contentMap.contents.size() + " contents");
175 if (transition(State.SESSION_ACCEPTED)) {
176 receiveSessionAccept(contentMap);
177 } else {
178 Log.d(Config.LOGTAG, String.format("%s: received session-accept while in state %s", id.account.getJid().asBareJid(), state));
179 //TODO out-of-order
180 }
181 }
182
183 private void receiveSessionAccept(final RtpContentMap contentMap) {
184 this.responderRtpContentMap = contentMap;
185 org.webrtc.SessionDescription answer = new org.webrtc.SessionDescription(
186 org.webrtc.SessionDescription.Type.ANSWER,
187 SessionDescription.of(contentMap).toString()
188 );
189 try {
190 this.webRTCWrapper.setRemoteDescription(answer).get();
191 } catch (Exception e) {
192 Log.d(Config.LOGTAG, "unable to receive session accept", e);
193 }
194 }
195
196 private void sendSessionAccept() {
197 final RtpContentMap rtpContentMap = this.initiatorRtpContentMap;
198 if (rtpContentMap == null) {
199 throw new IllegalStateException("initiator RTP Content Map has not been set");
200 }
201 setupWebRTC();
202 final org.webrtc.SessionDescription offer = new org.webrtc.SessionDescription(
203 org.webrtc.SessionDescription.Type.OFFER,
204 SessionDescription.of(rtpContentMap).toString()
205 );
206 try {
207 this.webRTCWrapper.setRemoteDescription(offer).get();
208 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createAnswer().get();
209 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
210 final RtpContentMap respondingRtpContentMap = RtpContentMap.of(sessionDescription);
211 sendSessionAccept(respondingRtpContentMap);
212 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription);
213 } catch (Exception e) {
214 Log.d(Config.LOGTAG, "unable to send session accept", e);
215
216 }
217 }
218
219 private void sendSessionAccept(final RtpContentMap rtpContentMap) {
220 this.responderRtpContentMap = rtpContentMap;
221 this.transitionOrThrow(State.SESSION_ACCEPTED);
222 final JinglePacket sessionAccept = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_ACCEPT, id.sessionId);
223 Log.d(Config.LOGTAG, sessionAccept.toString());
224 send(sessionAccept);
225 }
226
227 void deliveryMessage(final Jid from, final Element message) {
228 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": delivered message to JingleRtpConnection " + message);
229 switch (message.getName()) {
230 case "propose":
231 receivePropose(from, message);
232 break;
233 case "proceed":
234 receiveProceed(from, message);
235 break;
236 case "retract":
237 receiveRetract(from, message);
238 break;
239 default:
240 break;
241 }
242 }
243
244 private void receivePropose(final Jid from, final Element propose) {
245 final boolean originatedFromMyself = from.asBareJid().equals(id.account.getJid().asBareJid());
246 //TODO we can use initiator logic here
247 if (originatedFromMyself) {
248 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": saw proposal from mysql. ignoring");
249 } else if (transition(State.PROPOSED)) {
250 startRinging();
251 } else {
252 Log.d(Config.LOGTAG, id.account.getJid() + ": ignoring session proposal because already in " + state);
253 }
254 }
255
256 private void startRinging() {
257 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received call from " + id.with + ". start ringing");
258 xmppConnectionService.getNotificationService().showIncomingCallNotification(id);
259 }
260
261 private void receiveProceed(final Jid from, final Element proceed) {
262 if (from.equals(id.with)) {
263 if (isInitiator()) {
264 if (transition(State.PROCEED)) {
265 this.sendSessionInitiate();
266 } else {
267 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because already in %s", id.account.getJid().asBareJid(), this.state));
268 }
269 } else {
270 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed because we were not initializing", id.account.getJid().asBareJid()));
271 }
272 } else {
273 Log.d(Config.LOGTAG, String.format("%s: ignoring proceed from %s. was expected from %s", id.account.getJid().asBareJid(), from, id.with));
274 }
275 }
276
277 private void receiveRetract(final Jid from, final Element retract) {
278 if (from.equals(id.with)) {
279 if (transition(State.RETRACTED)) {
280 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
281 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": session with " + id.with + " has been retracted");
282 //TODO create missed call notification/message
283 jingleConnectionManager.finishConnection(this);
284 } else {
285 Log.d(Config.LOGTAG, "ignoring retract because already in " + this.state);
286 }
287 } else {
288 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": received retract from " + from + ". expected retract from" + id.with + ". ignoring");
289 }
290 }
291
292 private void sendSessionInitiate() {
293 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": prepare session-initiate");
294 setupWebRTC();
295 try {
296 org.webrtc.SessionDescription webRTCSessionDescription = this.webRTCWrapper.createOffer().get();
297 final SessionDescription sessionDescription = SessionDescription.parse(webRTCSessionDescription.description);
298 Log.d(Config.LOGTAG, "description: " + webRTCSessionDescription.description);
299 final RtpContentMap rtpContentMap = RtpContentMap.of(sessionDescription);
300 sendSessionInitiate(rtpContentMap);
301 this.webRTCWrapper.setLocalDescription(webRTCSessionDescription).get();
302 } catch (Exception e) {
303 Log.d(Config.LOGTAG, "unable to sendSessionInitiate", e);
304 }
305 }
306
307 private void sendSessionInitiate(RtpContentMap rtpContentMap) {
308 this.initiatorRtpContentMap = rtpContentMap;
309 this.transitionOrThrow(State.SESSION_INITIALIZED);
310 final JinglePacket sessionInitiate = rtpContentMap.toJinglePacket(JinglePacket.Action.SESSION_INITIATE, id.sessionId);
311 Log.d(Config.LOGTAG, sessionInitiate.toString());
312 send(sessionInitiate);
313 }
314
315 private void sendTransportInfo(final String contentName, IceUdpTransportInfo.Candidate candidate) {
316 final RtpContentMap transportInfo;
317 try {
318 final RtpContentMap rtpContentMap = isInitiator() ? this.initiatorRtpContentMap : this.responderRtpContentMap;
319 transportInfo = rtpContentMap.transportInfo(contentName, candidate);
320 } catch (Exception e) {
321 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": unable to prepare transport-info from candidate for content=" + contentName);
322 return;
323 }
324 final JinglePacket jinglePacket = transportInfo.toJinglePacket(JinglePacket.Action.TRANSPORT_INFO, id.sessionId);
325 Log.d(Config.LOGTAG, jinglePacket.toString());
326 send(jinglePacket);
327 }
328
329 private void send(final JinglePacket jinglePacket) {
330 jinglePacket.setTo(id.with);
331 //TODO track errors
332 xmppConnectionService.sendIqPacket(id.account, jinglePacket, null);
333 }
334
335 public RtpEndUserState getEndUserState() {
336 switch (this.state) {
337 case PROPOSED:
338 if (isInitiator()) {
339 return RtpEndUserState.RINGING;
340 } else {
341 return RtpEndUserState.INCOMING_CALL;
342 }
343 case PROCEED:
344 if (isInitiator()) {
345 return RtpEndUserState.CONNECTING;
346 } else {
347 return RtpEndUserState.ACCEPTING_CALL;
348 }
349 case SESSION_INITIALIZED:
350 return RtpEndUserState.CONNECTING;
351 case SESSION_ACCEPTED:
352 final PeerConnection.PeerConnectionState state = webRTCWrapper.getState();
353 if (state == PeerConnection.PeerConnectionState.CONNECTED) {
354 return RtpEndUserState.CONNECTED;
355 } else if (state == PeerConnection.PeerConnectionState.NEW || state == PeerConnection.PeerConnectionState.CONNECTING) {
356 return RtpEndUserState.CONNECTING;
357 } else if (state == PeerConnection.PeerConnectionState.CLOSED) {
358 return RtpEndUserState.ENDING_CALL;
359 } else {
360 return RtpEndUserState.ENDING_CALL;
361 }
362 case REJECTED:
363 case TERMINATED_DECLINED_OR_BUSY:
364 if (isInitiator()) {
365 return RtpEndUserState.DECLINED_OR_BUSY;
366 } else {
367 return RtpEndUserState.ENDED;
368 }
369 case TERMINATED_SUCCESS:
370 case ACCEPTED:
371 case RETRACTED:
372 case TERMINATED_CANCEL_OR_TIMEOUT:
373 return RtpEndUserState.ENDED;
374 case TERMINATED_CONNECTIVITY_ERROR:
375 return RtpEndUserState.CONNECTIVITY_ERROR;
376 }
377 throw new IllegalStateException(String.format("%s has no equivalent EndUserState", this.state));
378 }
379
380
381 public void acceptCall() {
382 switch (this.state) {
383 case PROPOSED:
384 acceptCallFromProposed();
385 break;
386 case SESSION_INITIALIZED:
387 acceptCallFromSessionInitialized();
388 break;
389 default:
390 throw new IllegalStateException("Can not accept call from " + this.state);
391 }
392 }
393
394 public void rejectCall() {
395 switch (this.state) {
396 case PROPOSED:
397 rejectCallFromProposed();
398 break;
399 default:
400 throw new IllegalStateException("Can not reject call from " + this.state);
401 }
402 }
403
404 public void endCall() {
405
406 //TODO from `propose` we call `retract`
407
408 if (isInState(State.SESSION_INITIALIZED, State.SESSION_ACCEPTED)) {
409 //TODO during session_initialized we might not have a peer connection yet (if the session was initialized directly)
410
411 //TODO from session_initialized we call `cancel`
412
413 //TODO from session_accepted we call `success`
414
415 webRTCWrapper.close();
416 } else {
417 //TODO during earlier stages we want to retract the proposal etc
418 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": called 'endCall' while in state " + this.state);
419 }
420 }
421
422 private void setupWebRTC() {
423 this.webRTCWrapper.setup(this.xmppConnectionService);
424 this.webRTCWrapper.initializePeerConnection();
425 }
426
427 private void acceptCallFromProposed() {
428 transitionOrThrow(State.PROCEED);
429 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
430 //Note that Movim needs 'accept', correct is 'proceed' https://github.com/movim/movim/issues/916
431 this.sendJingleMessage("proceed");
432
433 //TODO send `accept` to self
434 }
435
436 private void rejectCallFromProposed() {
437 transitionOrThrow(State.REJECTED);
438 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
439 this.sendJingleMessage("reject");
440 jingleConnectionManager.finishConnection(this);
441 }
442
443 private void sendJingleMessage(final String action) {
444 final MessagePacket messagePacket = new MessagePacket();
445 messagePacket.setTo(id.with);
446 messagePacket.addChild(action, Namespace.JINGLE_MESSAGE).setAttribute("id", id.sessionId);
447 Log.d(Config.LOGTAG, messagePacket.toString());
448 xmppConnectionService.sendMessagePacket(id.account, messagePacket);
449 }
450
451 private void acceptCallFromSessionInitialized() {
452 xmppConnectionService.getNotificationService().cancelIncomingCallNotification();
453 throw new IllegalStateException("accepting from this state has not been implemented yet");
454 }
455
456 private synchronized boolean isInState(State... state) {
457 return Arrays.asList(state).contains(this.state);
458 }
459
460 private synchronized boolean transition(final State target) {
461 final Collection<State> validTransitions = VALID_TRANSITIONS.get(this.state);
462 if (validTransitions != null && validTransitions.contains(target)) {
463 this.state = target;
464 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": transitioned into " + target);
465 updateEndUserState();
466 return true;
467 } else {
468 return false;
469 }
470 }
471
472 public void transitionOrThrow(final State target) {
473 if (!transition(target)) {
474 throw new IllegalStateException(String.format("Unable to transition from %s to %s", this.state, target));
475 }
476 }
477
478 @Override
479 public void onIceCandidate(final IceCandidate iceCandidate) {
480 final IceUdpTransportInfo.Candidate candidate = IceUdpTransportInfo.Candidate.fromSdpAttribute(iceCandidate.sdp);
481 Log.d(Config.LOGTAG, "sending candidate: " + iceCandidate.toString());
482 sendTransportInfo(iceCandidate.sdpMid, candidate);
483 }
484
485 @Override
486 public void onConnectionChange(PeerConnection.PeerConnectionState newState) {
487 Log.d(Config.LOGTAG, id.account.getJid().asBareJid() + ": PeerConnectionState changed to " + newState);
488 updateEndUserState();
489 }
490
491 private void updateEndUserState() {
492 xmppConnectionService.notifyJingleRtpConnectionUpdate(id.account, id.with, id.sessionId, getEndUserState());
493 }
494}