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